#include<iostream>
using namespace std;
class Test
{
public:
Test(int k)
{
this->m_k = k;//要常使用this 增加可读性
}
int getK() const //成员函数尾部出现const,修饰的是this指针
//表达只读指针,不可修改
{
//this就是指向调用该成员函数方法的对象地址
//this->m_k = 100;//this指针不是const Test *(本身不可修改,所指内容可修改)
//this++; //错误,说明this指针是一个常指针,Test *const
return this->m_k;
//return m_k; 一个意思
}
//static成员函数,只能返回static成员变量
static int s_getK()
{
return s_k;
}
private:
int m_k;
static int s_k;
};
int Test::s_k = 0;
int main()
{
Test t1(10);//Test(&t1,10)
Test t2(20);
t1.getK();// getI(&t1)
return 0;
}
总结:
成员函数尾部出现const,修饰的是this指针,表达只读指针,不可修改。
this就是指向调用该成员函数方法的对象地址。
this指针不是const Test *(本身不可修改,所指内容可修改),this++;错误,说明this指针是一个常指针,Test *const
static成员函数,只能返回static成员变量。