模板类:没有默认构造函数

时间:2011-05-13 10:26:10

标签: c++ templates constructor

我知道有一百万个关于此的帖子,但我仍然无法弄清楚为什么这不起作用= /

这一行:

test = new Test2<Test>;

给了我这个错误:

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

代码:

template<class PARENT>
class Test2;

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

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

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

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

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

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

有人可以帮助我吗?

3 个答案:

答案 0 :(得分:6)

在实例化时(即在Test构造函数内),到目前为止,所有编译器都是Test2<>前向声明;它还不知道可用的构造函数。

要解决,请移动Test2<> 的定义 Test之前的定义,或将Test构造函数的定义移到类定义之外(和之后 Test2<>)的定义。

答案 1 :(得分:0)

对我来说,你的代码给出(正确地,恕我直言)错误:

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

这与g ++ 4.5.1有关。在你说的时候:

test = new Test2<Test>;

Test2尚未定义,只是前向声明。

答案 2 :(得分:-1)

test = new Test2<Test>;正在Test的默认构造函数中执行。 这一行将调用没有参数的默认构造函数/构造函数。在调用上述语句时,Test的构造函数仍然不完整。

相关问题