模板类:没有默认构造函数
我知道有一百万篇关于此的帖子,但我仍然不明白为什么这不起作用=/
这一行:
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;
};
////////////////////////////
有人可以帮助我吗?
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>
class 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?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
在实例化点(即在
Test
构造函数内),编译器到目前为止所拥有的只是Test2
的前向声明;它还不知道有哪些构造函数可用。要解决此问题,请将
Test2<>
的定义移动到Test
的定义之前,或者移动Test
的定义code> 类定义之外的构造函数(以及Test2<>
的定义之后)。At the point of instantiation (i.e. inside the
Test
constructor), all the compiler has so far is a forward declaration ofTest2<>
; it doesn't yet know what constructors are available.To solve, either move the definition of
Test2<>
before that ofTest
, or move the definition of theTest
constructor outside the class definition (and after the definition ofTest2<>
).对我来说,您的代码给出了(正确地,恕我直言)错误:
This is with g++ 4.5.1。此时您会说:
Test2 尚未定义,仅向前声明。
For me, your code gives (correctly, IMHO) the error:
This is with g++ 4.5.1. At the point you say:
Test2 has not been defined, only forward declared.
test = new Test2;
行在 Test 的默认构造函数内执行。此行将调用不带参数的默认构造函数/构造函数。当调用上述语句时,Test 的构造函数仍然不完整。
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.