【问题标题】:Class constructor not working?类构造函数不起作用?
【发布时间】:2011-10-05 09:04:46
【问题描述】:

代码:

在类头文件中:

 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;

我的程序运行没有任何错误,但是构造函数没有初始化并且消息 不显示。有什么建议吗?

【问题讨论】:

  • 您从哪里得知constructor() 是任何类构造函数的名称?
  • 你在关注哪本书没有解释这些基本内容?

标签: c++ class constructor


【解决方案1】:

构造函数不是名为constructor 的函数。构造函数的“名称”是类本身的名称。注意构造函数不是普通函数,不能直接用名字引用,所以我把“名字”放在引号里。

你的代码应该如下:

//.h
class Coconuts
{
public:
    Coconuts();
};

//.cpp
Coconuts::Coconuts()
{
    cout << "\nYay coconuts are initialized";
};

【讨论】:

  • 为了完整性,同样适用于析构函数。
【解决方案2】:

那不是构造函数,构造函数只是类的名称:-

 class Coconuts 
 { 
 public:     
    Coconuts();  
 };

Coconuts::Coconuts()  
{      
    cout << "\nYay coconuts are initialized";  
};

【讨论】:

    猜你喜欢
    • 2012-09-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-11-22
    • 2018-07-17
    相关资源
    最近更新 更多