我是否可以像方法1中一样立即指定默认值,还是应该像方法2中那样使用重载的构造函数,还是像方法3/4中那样使用初始化列表?
哪种方法更好/正确的方法以及原因(所有方法似乎都可行)?
方法3和方法4有什么区别-我应该先指定构造函数声明,然后在类外部指定下一个定义,还是可以立即指定定义?
方法1:
#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");
}
我认为这两种方法都同样有效。根据每个类别的具体情况,每种方法都有其优点,优点和缺点。
无论是否需要默认构造函数参数,都需要以几乎相同的方式初始化对象时,使用默认值通常是最佳选择。指定默认值可避免重复代码。您只有一个构造函数。
另一方面,使用重载的构造函数可以以完全不同的方式完全干净地构造对象,具体取决于是否指定了参数。if
在这种情况下,强制类具有单个构造函数通常会导致用一堆语句对代码进行轰炸。
另外,不要忘记第三个选项:委托构造函数。在示例代码中使用该类:
Object() : Object("")
{
}
这种方法也有其固有的优点。
通常,对于哪种方法最好,目前尚无共识。最好考虑每个班级的个别要求,然后选择最适合该班级的方法。对于一个班级来说最好的方法可能不是另一个班级的最好方法。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句