C++ 类构造函数不工作?
代码: 类内头文件:C++ 类构造函数不工作?,c++,class,constructor,C++,Class,Constructor,代码: 类内头文件: class Coconuts { public: Coconuts constructor(); }; #include "Coconuts.h" #include <iostream> #include <string> using namespace std; Coconuts::constructor() { cout << "\nYay coconuts are i
class Coconuts
{
public:
Coconuts constructor();
};
#include "Coconuts.h"
#include <iostream>
#include <string>
using namespace std;
Coconuts::constructor()
{
cout << "\nYay coconuts are initialized";
};
在class.cpp文件中:
class Coconuts
{
public:
Coconuts constructor();
};
#include "Coconuts.h"
#include <iostream>
#include <string>
using namespace std;
Coconuts::constructor()
{
cout << "\nYay coconuts are initialized";
};
我的程序运行时没有任何错误,但是构造函数没有初始化,消息
不显示。建议,有人吗?构造函数不是名为
构造函数的函数。构造函数的“名称”是类本身的名称。请注意,构造函数不是普通函数,不能直接用名称引用,这就是我在引号中加上“name”的原因
您的代码应如下所示:
//.h
class Coconuts
{
public:
Coconuts();
};
//.cpp
Coconuts::Coconuts()
{
cout << "\nYay coconuts are initialized";
};
/.h
椰子类
{
公众:
椰子();
};
//.cpp
椰子::椰子()
{
cout这不是构造函数,构造函数只是类的名称:-
class Coconuts
{
public:
Coconuts();
};
及
椰子::椰子()
{
你从哪里读到的constructor()
是任何类构造函数的名称?你遵循的哪本书没有解释这些基本内容?为了完整起见,这同样适用于析构函数。