开发者

Class constructor not working?

Code:

In class header file:

 class Coconuts
{
public:
    Coconuts constructor();

};

In class .cpp file:

     #include "Coconuts.h"
  开发者_如何学C   #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?


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:

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

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


That's not a constructor, the constuctor is just the name of the class :-

 class Coconuts 
 { 
 public:     
    Coconuts();  
 };

and

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

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜