#include <iostream>
using namespace std;
class Person{
private:
string name;
bool gender;
int age;
public:
Person(string name_ ,bool gender_, int age_){
name = name_;
gender = gender_;
age = age_;
cout << name << "出生" <<endl;
}
~Person(){
cout<< name << "挂了" << endl;
}
Person(){
cout << "Person()" << endl;
}
Person(string name_){
name = name_;
}
Person(int age_){
age = age_;
}
/*拷贝构造函数*/
Person(const Person& that){
name = that.name;
gender = that.gender;
age = that.age;
cout << "copy" << endl;
}
void show(){
cout << "My name is " << name << endl;
cout << "I is " << (gender ? "man" : "women") << endl;
cout << "My age is " << age << endl;
}
string getName()const{//加const代表代码实现中没有改变成员
//只调用const成员函数
//如setName();则错误
cout << "getName()const" << endl;
return name;
}
string getName(){//有无const也可以重载函数
cout << "getName()" << endl;
return name;
}
void setName(string Name)
{
name = Name;
}
};
int main(int argc, const char *argv[])
{
const Person ps("tom",true,18);//ps只能使用const成员函数
cout << "name :" << ps.getName() << endl;//这里调用getName()const
Person ps2("tony",true,22);//ps2优先使用非const成员函数
cout << "name :" << ps1.getName() << endl;
return 0;
}
C++学习小记 const成员函数
最新推荐文章于 2024-11-15 16:06:58 发布