开发者

Template class: No default constructor

I know there are a million posts about this, but I still can't figure out why this isn't working =/

this line:

test = new Test2<Test>;

gives me this error:

error C2512: 'Test2<PARENT>' : no appropriate default constructor available
with
[
    PARENT=Test
]

code:

template<class PARENT>
cla开发者_StackOverflow中文版ss Test2;

////////////////////////////

class Test
{
public:
    Test2<Test> *test;

    Test()
    {
        test = new Test2<Test>;
    }
};

/////////////////////////////

template<class PARENT>
class Test2
{
public:
    PARENT *parent;
};

////////////////////////////

can someone help me out?


At the point of instantiation (i.e. inside the Test constructor), all the compiler has so far is a forward declaration of Test2<>; it doesn't yet know what constructors are available.

To solve, either move the definition of Test2<> before that of Test, or move the definition of the Test constructor outside the class definition (and after the definition of Test2<>).


For me, your code gives (correctly, IMHO) the error:

invalid use of incomplete type 'struct Test2<Test>'

This is with g++ 4.5.1. At the point you say:

test = new Test2<Test>;

Test2 has not been defined, only forward declared.


The line test = new Test2<Test>; is executing inside default constructor of Test. And this line will call the default constructor/constructor with no arguments. The constructor of Test is still not complete when the mentioned statement is being called.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜