1、C++类的普通成员函数都隐式包含一个指向当前对象的this指针,但静态成员函数不包含指向具体对象的指针。
2、this指针本质上是一个常指针 :类型 *const p;
3、员函数后面加const 修饰的不是函数,修饰的是隐藏的this指针,则此时该成员函数的this指针为指向常量的常指针:
const 类型 *const p;
class Test
{
public:
Test(int k)
{
this->m_k = k;
this->m_q = 0;
}
Test(int k, int q)
{
this->m_k = k;
this->m_q = q;
}
int getK() const // int getK(const Test *const this) // this 是一个常指针
{
//this++;
//this->m_k = 0; 在成员函数后面加const 修饰的不是函数,修饰的是隐藏的this指针
return this->m_k;
}
private:
int m_k;
int m_q;
};
4、函数返回引用与函数返回元素区别
函数返回引用(类的引用)可以继续调用类内函数和公有变量,函数返回元素无法继续调用。
class Test
{
public:
Test()
{
this->a = 0;
this->b = 0;
}
Test(int a, int b)
{
this->a = a;
this->b = b;
}
void printT()
{
cout << "a = " << a << ", b = " << b << endl;
}
Test TestAdd02(Test &another)//函数返回元素
{
//Test temp(this->a + another.getA(), this->b + another.getB());
Test temp(this->a + another.a, this->b + another.b);
return temp;
}
Test & TestAdd04(Test &another)//函数返回引用
{
this->a += another.a;
this->b += another.b;
//返回自己
return *this;
}//temp引用 = *this
private:
int a;
int b;
};
int main(void)
{
Test t1(10, 20);
Test t2(100, 200);
Test t5 = t1.TestAdd02(t2); //创建临时的开销
**(t1.TestAdd04(t2)).printT(); //t1的别名,其中t1.TestAdd04(t2)就返回t1本身
return 0;
}