在c++中常见的类构造方法
class Example{
private:
std::string name;
Entity entity;
public:
Example():name("ab"),entity(Entity(8)){
}
};
刚开始学习c++的时候,以为 :xxx()这只是 c++的代码风格而已。像java是在构造方法里去初始化成员变量
public Example(){
name = "ab";
entity = new Entity(8);
}
后来才发现不仅是代码风格的问题,还涉及类成员初始化的问题
#include<iostream>
using namespace std;
class Entity{
public:
Entity(){
cout<< "Create Entity"<< endl;
}
Entity(int num){
cout<< "Create Entity"<< num << endl;
}
};
class Example{
private:
std::string name;
Entity entity;
Example(){
entity = Entity(8);
}
};
int main(){
Example example;
return 0;
}
我们运行上面这段代码会发现entity 的两个构造方法都会被调用。
Create Entity
Create Entity8
而下面这种方法只会调用一次构造方法。
Example():name("ab"),entity(Entity(8)){}
所以,我们在编写c++代码的时候要注意成员变量的初始化位置哦