|
马上注册,结交更多好友,享用更多功能^_^
您需要 登录 才可以下载或查看,没有账号?立即注册
x
本帖最后由 这是她 于 2020-5-12 18:14 编辑
Little by little,one travels far.
this指针-------指向被调用的成员函数所属对象
1、this指针是隐含每一个非静态成员函数内的一种指针;
2、this指针不需要定义,直接使用即可;
this指针的用途:
1、当形参和成员变量同名时,可用this指针来区分;
2、在类的非静态成员函数中返回对象本身,可用return *this;
- #include<iostream>
- using namespace std;
- class Meat
- {
- public:
- int price;
-
- Meat(int price)
- {
- //当形参和成员变量同名时,可用this指针来区分;
- this->price = price;
- }
-
- Meat& MeatAddprice(Meat r)
- {
- this->price += r.price;
- //返回对象本身
- return *this;
- }
- };
- int main()
- {
- Meat pork(45);
- cout << "The price of pork : " << pork.price << endl;
-
- Meat beef(56);
- beef.MeatAddprice(pork);
- beef.MeatAddprice(pork).MeatAddprice(pork).MeatAddprice(pork).MeatAddprice(pork);//如果希望这条语句可以顺利运行,那么这个成员函数的返回值类型应该是对象,所以嘞,我们在这返回引用,而不是返回一个值
- cout << "The price of beef is : " << beef.price << endl;
-
- return 0;
- }
复制代码
const修饰成员函数
常函数:
1、成员函数后加const----该成员函数->常函数;
2、常函数内不可以修改成员属性;
3、成员属性声明时加关键字mutable-----在常函数中依然可以修改;
常对象:
1、声明对象前加const----该对象->常对象;
2、常对象只能调用常函数;
- #include<iostream>
- using namespace std;
- class Meat
- {
- public:
- int m_price;
- int m_mass;
- mutable int m_size; //加入mutable关键字,即使在常函数中也可以修改他的值
-
- Meat(int price,int mass)
- {
- this->m_price = price;
- this->m_mass = mass;
- }
-
- //this指针的本质--指针常量,指针的指向是不可以修改的
- //在成员函数后面加const,修饰的是this的指向,让指针指向的值也不可以修改
- void showmass(int mass) const
- {
- this->m_size = 888;//这个语句是可以执行的
- this->m_mass = 999;//如果成员函数没有const,这条语句是可以执行的;加入const以后,指针指向的值是不可以修改的
- this->m_mass = NULL;//this指针是不可以修改指针的指向的
- cout << "Eating meat!!!!!!" << endl;
- }
-
- void showprice()
- {
- //防止空指针
- if(this == NULL)
- {
- return;
- }
-
- cout << "price : " << this->m_price << endl;
- }
-
- };
- int main()
- {
- Meat *pork = NULL;
- pork->showmass(555);
- //pork->showprice();//传入空指针会出错
-
- const Meat beef(1,1);//在对象前面加入const,变成常对象
- beef.m_price = 666;//不可以修改
- beef.m_size = 333;//可以修改
-
- //常对象只能调用常函数
- beef.showmass(555);//√
- beef.showprice(222,111); //× 常对象不可以调用普通成员函数,因为普通成员函数可以修改属性
-
-
- return 0;
- }
复制代码
渣渣等待大佬赐教
|
|