注意事项
- 尽量用括号的形式去初始化成员变量,避免成员变量的被多次初始化
- 括号形式构造成员变量: 顺序需和成员变量定义顺序保持一致
#include<iostream>
class Entity {
public:
int m_Score;
std::string m_Name;
//以属性名称 + 括号 的形式在构造函数中为属性赋值
Entity() :
//这个顺序需要和上面属性的顺序保持一致
m_Score(0), m_Name("Unknown") {
}
Entity(const std::string& name) {
m_Name = name;
}
};
void testOrderConstruct() {
Entity e0;
std::cout << e0.m_Name << " | " << e0.m_Score << std::endl;
Entity e1("Cherno");
std::cout << e1.m_Name << " | " << e1.m_Score << std::endl;
}
class Example {
public:
Example() {
std::cout << "Create Example." << std::endl;
}
Example(int x) {
std::cout << "Create Example with " << x << std::endl;
}
};
class Entity2 {
public:
std::string m_Name;
//这里会调用其默认构造函数
Example example;
//以属性名称 + 括号 的形式在构造函数中为属性赋值
Entity2() :
//这个顺序需要和上面属性的顺序保持一致
m_Name("Unknown"),
//保障只会调用此构造函数,上面的属性不会调用Example的空构造函数
//example(Example(8)) {
//简写,不会再去调用Example的空构造方法
example(8)
{
//在构造函数体中这种写法会调用2次,1次带数字的构造函数,一次空构造函数
//example = Example(8);
}
Entity2(const std::string & name): m_Name(name)
{
}
};
void testEntity2() {
//调用了Example的构造函数两次
Entity2 e0;
}
int main() {
//testOrderConstruct();
testEntity2();
std::cin.get();
}