构造函数和/或析构函数问题 [英] Constructor and/or Destructor problem

查看:82
本文介绍了构造函数和/或析构函数问题的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述



我有以下课程

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 the SomeOtherClass 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.


这篇关于构造函数和/或析构函数问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆