2012-10-07 31 views
1

下面是我的.h文件中RGD:如何为类私有初始化的默认值

#include <iostream> 
#include <string> 

using namespace std; 

class ClassTwo 
{ 
private: 
string sType; 
int x,y; 
public: 
void setSType(string); 
void setX(int); 
void setY(int); 

string getSType(); 
int getX(); 
int getY(); 
}; 

我想建造2构造函数。

哪个构造函数1将没有参数,将所有int值初始化为0,并将字符串初始化为空字符串。

构造函数2将使用get方法获取sType,x和y参数。

但我怎么做到这一点。

ClassTwo() : sType(), x(), y() {} 

您可以选择与初始化为清楚更明确:

ClassTwo() : sType(""), x(0), y(0) {} 

你可以,我应该在我的cpp文件或.h文件中

+0

见【什么是会员变量列表后面的冒号在一个构造函数好?](http://stackoverflow.com/questions/210616/what-is-the-member-variables-list-after-the-colon-in-a-constructor-good -for?lq = 1) –

回答

1

对于默认的构造函数代码此也省略了字符串的初始化,其默认值为""

对于第二构造,最好是没有setter方法实现:

ClassTwo(const std::string& s, int x, int y) : sType(s), x(x), y(y) {} 

无论你在标题中实施或在.cpp是你。我认为在头文件中实现这样简单的构造函数没有什么不利之处。

我建议你使用数据成员的命名约定。诸如xy之类的名称可能会导致代码中的其他地方发生冲突。

1

标题用于定义。包括标题不必知道任何实现代码(除非你使用模板,这是一个不同的故事...)

不管怎么说,2层构造:

public: 
ClassTwo() : sType(""), x(0), y(0) {} 
ClassTwo(string _type) : sType(_type), x(0), y(0) {} 
+0

我应该在哪里初始化这个构造函数?它是在.h文件还是.cpp文件中 – user1726440