类构造函数不起作用?
代码:
在类头文件中:
class Coconuts
{
public:
Coconuts constructor();
};
在类 .cpp 文件中:
#include "Coconuts.h"
#include <iostream>
#include <string>
using namespace std;
Coconuts::constructor()
{
cout << "\nYay coconuts are initialized";
};
在 main() 中:
Coconuts Object1;
我的程序运行时没有任何错误,但构造函数未初始化并且消息 不显示。有建议吗?
Code:
In class header file:
class Coconuts
{
public:
Coconuts constructor();
};
In class .cpp file:
#include "Coconuts.h"
#include <iostream>
#include <string>
using namespace std;
Coconuts::constructor()
{
cout << "\nYay coconuts are initialized";
};
In main():
Coconuts Object1;
My program runs without any erros whatsoever, but the constructor isn't initialized and the message
is not displayed. Suggestions, anyone?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
构造函数不是名为
constructor
的函数。构造函数的“名称”是类本身的名称。请注意,构造函数不是普通函数,不能通过名称直接引用,这就是为什么我将“名称”放在引号中。您的代码应如下所示:
Constructors are not functions named
constructor
. The "name" of a constructor is the name of the class itself. Note that constructors are not normal functions and cannot be directly referenced by name, which is why I put "name" in quotation marks.Your code should be as follows:
这不是构造函数,构造函数只是类的名称:-
并且
That's not a constructor, the constuctor is just the name of the class :-
and