【发布时间】:2016-07-06 15:11:51
【问题描述】:
我可以像在方法 1 中那样一次指定默认值,还是应该像在方法 2 中那样使用重载构造函数,或者像在方法 3/4 中那样使用初始化列表?
哪种方法更好/正确,为什么(所有方法似乎都有效)?
方法 3 和方法 4 有什么区别 - 我应该先指定构造函数声明,然后在类外定义下一个定义,还是可以立即指定定义?
方法一:
#include <iostream>
#include <string>
using namespace std;
const string GLOBAL_VAR = "XXX";
class Object
{
private:
string var;
public:
Object(string inArg = "yyy")
{
this->var = GLOBAL_VAR + inArg + "ZZZ";
}
string show()
{
return this->var;
}
};
int main() {
Object o1, o2("www");
cout << o1.show() << endl;
cout << o2.show() << endl;
system("pause");
}
方法 2:
#include <iostream>
#include <string>
using namespace std;
const string GLOBAL_VAR = "XXX";
class Object
{
private:
string var;
public:
Object()
{
this->var = GLOBAL_VAR + "yyyZZZ";
}
Object(string inArg)
{
this->var = GLOBAL_VAR + inArg + "ZZZ";
}
string show()
{
return this->var;
}
};
int main() {
Object o1, o2("www");
cout << o1.show() << endl;
cout << o2.show() << endl;
system("pause");
}
方法 3:
#include <iostream>
#include <string>
using namespace std;
const string GLOBAL_VAR = "XXX";
class Object
{
private:
string var;
public:
//declaration:
Object();
Object(string);
string show()
{
return this->var;
}
};
//definition:
Object::Object() : var(GLOBAL_VAR + "yyyZZZ") {}
Object::Object(string inArg) : var(GLOBAL_VAR + inArg + "ZZZ"){}
int main() {
Object o1, o2("www");
cout << o1.show() << endl;
cout << o2.show() << endl;
system("pause");
}
方法 4:
#include <iostream>
#include <string>
using namespace std;
const string GLOBAL_VAR = "XXX";
class Object
{
private:
string var;
public:
//declaration and definition in one:
Object() : var(GLOBAL_VAR + "yyyZZZ") {}
Object(string inArg) : var(GLOBAL_VAR + inArg + "ZZZ") {}
string show()
{
return this->var;
}
};
int main() {
Object o1, o2("www");
cout << o1.show() << endl;
cout << o2.show() << endl;
system("pause");
}
【问题讨论】:
-
在 C++ 中,您不需要
this->符号。直接访问成员变量。 -
方法 2 和 3 之间确实没有区别。方法 2 和 4 之间的唯一区别是一个使用初始化列表,而另一个不使用。这意味着方法 2、3 和 4 是相同的。至于哪个是“最好的”,那就看你怎么想了,这是主观的,见仁见智。
标签: c++ constructor default-value initialization-list