使用公共函数将对象引用传递到不同的类对象数组中

Pass object reference into different class object array using public function

本文关键字:对象 数组 函数 对象引用      更新时间:2023-10-16

给定类A和类B。我需要使用 cpp 文件中所示的"add"函数将类 B 的对象引用存储在类 A 的对象数组中。

我应该能够使用 cpp 文件中所示的"->"来调用 B 类的"打印"函数。

编译时错误:void* 不是指向对象的指针类型

那么我该如何解决此错误呢?

=====================================================================================================================================================================================================================================================

===

头文件

// ABC.h
class A{
     private:
        size_t size_;
        void * a_[256];
        static int index_;
    public:
        void add(void * obj);
        void * operator[](int x){
            return a_[x];
        }

};
class B {
    private:
        const char * f_;
        const char * l_;
    public:
        B(const char * fn, const char * loc ):f_(fn), l_(loc){ A(); };
        void print();
};

CPP 文件

#include "ABC.h"
int A::index_ = 0;
inline void A::add(void* obj){
    void * insertionPoint = static_cast<char *>(a_[index_]) + ( size_ * index_ );
    memcpy( insertionPoint, obj,  size_);
    ++index_;
}
inline void B::print(){
    ...
}
int main()
{
    A a;
    B b( "Name", "Some string");
    a.add( &b );
    a[0]->print(); // <-- This should be an object reference to B, but it is producing the error.
    return 0;
}

输出:

命名一些字符串

以下方法没有意义:

virtual void add(A * obj){
    *this = dynamic_cast<void*>(obj);
}

如果您想在A中存储指向其他A实例的指针,请创建一个指针数组,您将在其中保存它们,尝试"替换"当前实例(即 *this =...毫无意义。

另请注意,如果要检查A*是否指向B实例,dynamic_cast有意义:

A* a = new B();
// in compile time it's A*, but does it really point to instance of B? :
B* b = dynamic_cast<B*>(a);

你为什么不从更简单的东西开始呢?比方说:

class A {
public:
    virtual void print() { std::cout << "a"; }
};
class B : public A {
public:
    void print() /* const */ { std::cout << "b"; }
};

用作:

A* a = new A();
A* b = new B();
a->print();
b->print();

它(就目前而言)输出ab.然后你可以将Bprint()更改为const,并意识到方法的const性实际上很重要。

解决方案涉及上述所有评论的建议

比较问题和答案之间的差异,以全面查看解决方案。

我需要做的是将A类的私人a_成员更改为A型:A * _a[256]
下一个: 我需要将运算符 [] 和 add 方法的参数更改为类型 A,以及:A * 运算符[](A * obj)
下一个:我需要添加一个虚拟的 void print() 用于继承目的到类 A。
最后:需要继承 A 类 B 类

下面是工作代码

注意:我不确定这段代码是否完全安全或正确处理内存问题,但我知道它打印是为了输出它打算打印的内容。

=====================================================================================================================================================================================================================================================

===

头文件

// ABC.h
class A{
     private:
        size_t size_;
        A * a_[256];
        static int index_;
    public:
        void add(A * obj);
        A * operator[](int x); // Any subclass object reference of A can be assigned now. 
        virtual void print()const; // Virtual tells the compiler to look for other void print methods first.

};
class B : public A{
    private:
        const char * f_;
        const char * l_;
    public:
        B(const char * fn, const char * loc ):f_(fn), l_(loc){ A(); };
        void print()const;
};

CPP 文件

#include "ABC.h"
int A::index_ = 0; // Need to call this here because it is declared static in Class A and can be used dynamically. 
inline A * A::operator[](int x){
    return a_[x]; // Implements operator[], so class A can act like a container.
}
inline void A::add(A* obj){
    a_[index_] = obj; // Adds a base or subclass object reference to class A object array.
    ++index_; // Need this to remember current index of object reference A's array.
}
inline void A::print()const{}
inline void B::print()const{
    std::cout <<  "B " << firstname_ << " works in " << location_ << std::endl;
}
int main()
{
    A a;
    B b( "Name", "Some string");
    a.add( &b );
    a[0]->print();
    return 0;
}

输出:

命名一些字符串