Rgd:如何初始化类private的默认值

时间:2012-10-07 09:18:37

标签: c++

以下是我的.h文件

#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 set来获取sType,x和y参数。

但我如何实现这一目标。我应该在我的cpp文件或.h文件中编码吗

2 个答案:

答案 0 :(得分:1)

对于默认构造函数:

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

为了清晰起见,您可以选择更明确地进行初始化:

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

您也可以省略字符串的初始化,默认为""

对于第二个构造函数,最好在没有setter的情况下实现:

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

是否在标题中实现或.cpp取决于您。我认为在标题中实现这样的简单构造函数没有任何缺点。

我建议您对数据成员使用命名约定。 xy等名称可能会导致代码中的其他位置发生冲突。

答案 1 :(得分:1)

标题用于定义。包含标题的代码不必知道任何实现(除非您使用的是不同故事的模板...)

无论如何,2个构造函数:

public:
ClassTwo() : sType(""), x(0), y(0) {}
ClassTwo(string _type) : sType(_type), x(0), y(0) {}
相关问题