C++ 谁能帮我理解这个错误?“隐式声明的'classA::classA()'的定义”
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/5765780/
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
Can anyone help me understand this error? "definition of implicitly-declared ‘classA::classA()’"
提问by darko
Heres the code:
代码如下:
#include <cstdlib>
#include <iostream>
using namespace std;
class classA
{
protected:
void setX(int a);
private:
int p;
};
classA:: classA()
{ //error here.
p = 0;
}
void classA:: setX(int a)
{
p = a;
}
int main()
{
system("PAUSE");
return EXIT_SUCCESS;
}
回答by Nawaz
You forgot to declare the constructor in the class definition. Declare it in public
section of the class (if you want clients to create instance using it):
您忘记在类定义中声明构造函数。public
在类的部分中声明它(如果您希望客户端使用它创建实例):
class classA
{
public:
classA(); // you forgot this!
protected:
void setX(int a);
private:
int p;
};
Now you can write its definition outside the class which you've already done.
现在你可以在你已经完成的类之外编写它的定义。
回答by Johannes Schaub - litb
class classA
{
protected:
classA(); // you were missing an explicit declaration!
void setX(int a);
private:
int p;
};
classA:: classA()
{
p = 0;
}
回答by Mahesh
classA
has no member named classA()
to implement.
classA
没有命名classA()
要实现的成员。
class classA
{
// ....
public:
classA() ; // Missing the declaration of the default constructor.
};
回答by Mikhail Semenov
An empty constructor is provided by default: this is correct. But if you redefine it, it's not a default constructor any more. You have to declare and define it. If you only declare it (without the body), it's incorrect: you have to define it as well. If you define it without a declaration in the class, it's an error as well. You can though, "combine" declaration and definition by writing as follows:
默认情况下提供一个空的构造函数:这是正确的。但是如果你重新定义它,它就不再是默认构造函数了。你必须声明和定义它。如果你只声明它(没有主体),这是不正确的:你也必须定义它。如果你在类中没有声明的情况下定义它,它也是一个错误。但是,您可以按如下方式“组合”声明和定义:
class classA
{
// ....
public:
classA() { p = 0;}
};
or in this case even better:
或者在这种情况下甚至更好:
class classA
{
// ....
public:
classA():p(0) {}
};