this指针
文章目录
- this指针是常量指针,不可修改
- 成员函数后加const
- 静态成员函数没有this指针
- 返回对象本身用 *this
this指针传递的是当前对象的指针,这样每个对象操作自己的成员变量
this指针是常量指针,不可修改
class Goods
{
public:Goods(int w):m_weight(w)
{
}
int Get()
{
this++; //报错,必须是可修改的左值 ,证明传递的是: Goods* const this
return m_weight;
}
private:
int m_weight;
};
成员函数后加const
如果一个成员函数后面加const修饰,修饰的是this指针,表示不可以通过this指针修改其对象内容
class Goods
{
public:Goods(int w):m_weight(w)
{
}
int Get()const //不能通过this进行修改值, 传递的是: const Goods* const this
{
m_weight++; //报错,this->m_weight++;
return m_weight;
}
private:
int m_weight;
};
class Student
{
friend Student operator+(const Student& s1, const Student& s2);
public:
Student(int id) :m_id(id) { }
int GetID()const
{
return m_id;
}
private:
int m_id;
};
Student operator+(const Student& s1,const Student& s2)
{
Student tmp(s1.GetID()+s2.GetID()); //如果Student::GetID后面不加const报错,因为将GetID(Student* const s),将const s1赋值給s报错
return tmp;
}
int main(void)
{
Student A(1);
Student B(2);
Student C = A + B;
cout << C.GetID() << endl;
return 0;
}
静态成员函数没有this指针
- 静态成员函数只能访问静态成员变量,因为静态成员函数不属于对象,所以没有this指针
返回对象本身用 *this
#include "stdafx.h"
#include <iostream>
using namespace std;
class Goods
{
public:
Goods(int w):m_weight(w)
{
}
Goods& Add(Goods& another) //返回是自身引用,还可以做左值
{
m_weight+=another.m_weight;
return *this;
}
void Print()
{
cout << m_weight << endl;
}
private:
int m_weight;
};
int main(void)
{
Goods A1(100);
Goods A2(100);
Goods A3(100);
A1.Add(A2).Add(A3);
A1.Print(); //300
return 0;
}
还没有评论,来说两句吧...