0

I know that this is probably a pointless question because it is obvious that class BASE does not have a function called pass_A, it is actually declared in another class called A and I though that using inheritance and polymorphism would allow the BASE class to see itself and the object of type A. I definitely want an object of type A to be able to call the class A from within BASE as well as BASE being declared the way it is now in init_BASE. My ultimate question is is this possible? Maybe I'm not using virtuals or something else is wrong.

What I want is for the object POLY_TYPE to be able to contain both BASE and A class types. Anyways heres the error message and the code below it.

EDITED Look at solution instead.

4

2 回答 2

4

Compiler is telling you the truth - BASE indeed does not have a member called pass_A.

Here POLY_TYPE->pass_A(new NODE()); you're trying to call pass_A through a pointer to BASE. Compiler will look up the method based on the static type of the object (that is, BASE as opposed to dynamic type, which is A - why all the caps, btw?).

You'll need to add a virtual pass_A method to the base class if you want this work.

(I'm intentionaly leaving out the fact that BASE is a template - the type is really BASE<T> where T is whatever type you instantiate the template with. It is not directly related to the problem)

于 2013-08-01T10:35:55.663 回答
1

如果这就是您需要做的全部,那么在绝对必须之前不要丢弃类型信息:

A<T>* a = new A<T>;
a->pass_A(new NODE);
POLY_TYPE = a;

编辑:

您没有在更新中发布任何错误消息 - 有趣的是,有这么多在这里提问的人认为实际错误无关紧要 - 但您也有类型问题。
由于您将 a 传递NODE*给 pass_A,因此模板参数必须是NODE*,而不是NODE

以下编译(使用我的调整清理没有虚拟的版本):

class NODE
{
public:
    NODE(){}
    ~NODE(){}
    NODE&  operator=(const NODE&) { return *this; }
};

template <class T>
class A;

template <class T>
class BASE
{    
public:
    BASE(){}
    BASE(int mode)
    {
        if(mode == 1)
        {
            init_BASE();
        }
        else if(mode == 0)
        {
            init_A();
        }
    }
private:
    void init_BASE()
    {
        POLY_TYPE = new BASE<T>;
    }

    void init_A()
    {
        A<T>* a = new A<T>;
        a->pass_A(new NODE);
        POLY_TYPE = a;
    }

    BASE* POLY_TYPE;
};

template <class T>
class A : public BASE<T>
{
public:
    void pass_A(T DATA)
    {
        this->DATA = DATA;
    }
private:
    T DATA;
};

int main()
{
    BASE<NODE*> base(1);
    return 0;
}
于 2013-08-01T11:17:39.623 回答