一。类的四种初始化方式
1.不使用构造函数初始化类
使用函数引用来初始化类
class MM {
public:string& getname() {return name;}int& getage() {return age;}void print() {cout << "name: " << name << endl << "age: " << age << endl;}
private:string name;int age;
};
int main() {MM mm;mm.getname()= "wangjianghui";mm.getage()= 25;mm.print();return 0;
}
结果:
注意:
函数引用是:
正确: int& getage() { return age;}//直接引用私有属性直接修改他。
错误: int& getage(int age) { return age;}
2.使用构造函数初始化类
使用构造函数初始化类,就算不写构造函数,C++也会自己有一个默认构造函数,类似下面
MM() {}
class MM {
public:MM() { cout<<"默认构造函数已经使用" << endl; }MM(string a, int b) {name = a;age = b;}void print() {cout << "name: " << name << endl << "age: " << age << endl;}
private:string name;int age;
};
int main() {MM mm("wangjianghui",25);mm.print();cout << "使用默认构造函数" << endl;MM mm2;return 0;
}
3.拷贝构造函数
class MM {
public:MM() {}MM(string a, int b) {name = a;age = b;}MM(MM& object) {name = object.name;age = object.age;}void print() {cout << "name: " << name << endl << "age: " << age << endl;}
private:string name;int age;
};
int main() {MM mm("wangjianghui",25);MM mm1;mm1 = mm;mm.print();return 0;
}
注意:
MM(MM& object) {name = object.name;age = object.age; }
如果不写&
MM(MM object) {name = object.name;age = object.age; }
会报错, “MM”: 非法的复制构造函数: 第一个参数不应是“MM”
4.初始化参数列表
class MM {
public:MM(string s_name, int i_age) :name(s_name), age(i_age) {}void print() {cout << name <<'\t' << age << endl;}
private:string name;int age;
};
int main() {MM mm("wangjianghui", 25);mm.print();return 0;
}