c++对象模型和this指针
成员变量和成员函数分开存储
属于类的对象上:成员变量
不属于类的对象上:成员函数,静态变量,静态函数
再补充空对象的概念:空对象在内存中默认占一个字节,便于分辨不同的空对象,每个空对象在内存中占据的内存应是独一无二的
this指针的概念
this指针指向被调用函数的所属对象
this指针隐含在每个非静态成员函数中
this指针不需要定义,直接使用即可
this指针的用途:
形参和成员变量同名时,可用this指针区分
在类的非静态函数中返回类的对象本身,可使用return *this
class person {
public:
person(int age) {
//形参和成员变量同名时,用于区分它们
this->age = age;
}
//在类的非静态成员函数返回本身return *this;
person& person_add_age(person&p) {
this->age += p.age;
return *this;//如果没有&,返回的是一个拷贝的值,并不是原来的那个p1
}
int age;
};
void test01() {
person p1(10);
person p2(10);
//链式编程(返回对象本身可用,返回值则编译器报错)
p1.person_add_age(p2).person_add_age(p2).person_add_age(p2);
cout << p1.age << endl;
}
int main() {
test01();
}
空指针访问成员函数
c++中空指针也可以访问成员函数,但要注意有没有用到this指针
如果使用了this指针,要加以判断代码的健壮性(由于对象指针为空,导致this指针也为空,所有对this指针解引用的操作都是非法的,对空指针也是)
//空指针访问成员函数
class person {
public:
void persontest01() {
cout << "go to" << endl;
}
void persontest02() {
if (this == NULL) {
return;
}
cout << m_age << endl;
}
int m_age;
};
int main()
{
person* p = NULL;
p->persontest01();
p->persontest02();
}
const修饰成员函数
被const修饰的成员函数和成员变量称为常函数和常变量
常函数
语法:返回值类型 函数名 ()const {}
常函数中的属性不可修改
当属性被关键词mutable修饰时,在常函数中可修改
常对象
语法:const 数据类型 变量名
常对象只能调用常函数
//const修饰成员函数和对象
class person {
public:
//1.m_a=this->m_a
//2.this的完整写法 成员函数:person* const this 常函数:const person* const this
void showperson()const {
//this=NULL;this是指针常量,指向不可改变
//m_a = 100;不可修改
m_b = 100;//特殊变量,被mutable关键字修饰,可修改
}
void showperson2() {
m_a = 100;
}
int m_a=10;
mutable int m_b;
};
int main()
{
const person p;
//p.m_a = 100;不可修改
p.m_b = 100;//特殊变量,被mutable关键字修饰,可修改
p.showperson();
//p.showperson2();常对象只能调用常函数 因为普通函数可以修改普通变量的值与常对象不可修改起了冲突
}