与构造函数/析构函数定义相关的 c++ 编译错误
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/708008/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
c++ compiling error related to constructor/destructor definition
提问by Michael Burr
I'm trying to define the constructor and destructor of my class but I keep getting the error:
我正在尝试定义我的类的构造函数和析构函数,但我不断收到错误消息:
definition of implicitly-declared 'x::x()'
隐式声明的 'x::x()' 的定义
What does it mean?
这是什么意思?
Part of the code:
部分代码:
///Constructor
StackInt::StackInt(){
t = (-1);
stackArray = new int[20];
};
///Destructor
StackInt::~StackInt(){
delete[] stackArray;
}
回答by Michael Burr
In the class declaration (probably in a header file) you need to have something that looks like:
在类声明中(可能在头文件中),您需要具有如下所示的内容:
class StackInt {
public:
StackInt();
~StackInt();
}
To let the compiler know you don't want the default compiler-generated versions (since you're providing them).
让编译器知道您不想要默认的编译器生成的版本(因为您提供了它们)。
There will probably be more to the declaration than that, but you'll need at least those - and this will get you started.
声明中可能会有更多内容,但您至少需要这些 - 这将使您开始。
You can see this by using the very simple:
您可以通过使用非常简单的方式看到这一点:
class X {
public: X(); // <- remove this.
};
X::X() {};
int main (void) { X x ; return 0; }
Compile that and it works. Then remove the line with the comment marker and compile again. You'll see your problems appear then:
编译它,它的工作原理。然后删除带有注释标记的行并再次编译。然后你会看到你的问题出现:
class X {};
X::X() {};
int main (void) { X x ; return 0; }
qq.cpp:2: error: definition of implicitly-declared `X::X()'
回答by taronish4
Another thing to keep in mind is that everything that the constructor accesses must be public. I have gotten this error before.
要记住的另一件事是构造函数访问的所有内容都必须是公共的。我以前遇到过这个错误。
class X{
T *data;
public: // <-move this to include T *
X();
~X();
}
This code still have the error because in my constructor I had the following:
这段代码仍然有错误,因为在我的构造函数中,我有以下内容:
X::X(){data = new T();
Which meant that although I had made the constructor and destructor public, the data they were working with was still private, and I still got the "definition of implicitly-declared" error.
这意味着虽然我已经公开了构造函数和析构函数,但它们使用的数据仍然是私有的,我仍然收到“隐式声明的定义”错误。