构造函数和/或析构函数问题
问题描述:
我有以下课程
Hi,
I have following class
class B
{
SomeOtherClass* A;
B() : A(new SomeOtherClass) {}; // default constructor
~B()
{
delete A;
}
};
如果我以以下方式声明B对象,在
inside
main
里面就可以了:
if I declare B object in the following way all is ok:
B object();
如果我这样声明:
If I declare it like this:
B object;
我收到一个错误(与致命错误LNK1120:1个未解决的外部组件"有关).
请注意,如果我在析构函数中删除删除A",则可以执行以下声明:
I get an error (related to "fatal error LNK1120: 1 unresolved externals").
Please note that if I remove "delete A" in the destructor, then I am allowed to perform following declaration:
B object;
为什么会这样呢?有人可以帮忙吗?谢谢.
最好的问候.
Why is this happening? Can someone help?? Thanks.
Best Regards.
答
您有两个问题:
1)声明和定义混乱
2)SomeOtherClass
类的某些析构函数问题
关于第1项,在C ++中,如果可以将构造解释为声明,则将其视为声明.
因此:
You have two issues:
1) confusion on declaration and definition
2) some destructor issues with theSomeOtherClass
class
To item 1) In C++, if a construct can be interpreted as declaration, it is taken as declaration.
Therefore:
B object1(); // declares function "object1" that takes no argument and returns B
B object2; // defines variable "object2" and calls the default constructor
正如您在另一种解决方案的评论中提到的那样,项目2)似乎已解决.
干杯
Andi
Item 2) seems to be solved as you mentioned in a comment of another solution.
Cheers
Andi
尝试在您的B类声明的末尾括号后放置一个分号.
Try and place a semicolon after the end-bracket of your class B declaration.
class B
{
SomeOtherClass* A;
B() : A(new SomeOtherClass) {}; // default constructor
~B()
{
delete A;
}
};
好的.这可能是由于您的构造函数未公开.
您的文件如何组织?您的课程是否有单独的.h文件?您得到的错误可能是由于编译器找不到元素之一的定义(类本身或其方法之一,甚至是SomeOtherClass.
如果您发布了完整的错误消息,将会有所帮助.
Alright. It might be due to your constructor not being public.
How are your files organized? Do you have a separate .h file for your classes? The error your''re getting is probably becuase the compiler cannot find the definition of one of your elements (either the class itself, or one of its methods, or maybe even your SomeOtherClass.
It would help if you posted your complete error message.