四.类和对象
3.C++对象模型和This指针
一.成员变量和成员函数分开储存
- 类内对象成员和成员函数分开储存
- 只有非静态成员变量才属于类的对象上
- 非静态成员变量属于类的对象上
- 静态成员变量不属于类对象上
- 非静态成员函数不属于类对象上
- 静态成员函数不属于类对象上
- 空对象占用内存空间为1,c++编译器会给每个空对象分配一个字节的空间,是为了区分对象占内存的位置,每个空对象也有一个独一无二的内存地址
二.This指针概念
- this指针是隐含每一个非静态成员函数内的一种指针
- this指针指向被调用的成员函数所属的对象
- this指针不需要定义,直接使用即可
this指针的用途
- 当形参和成员变量同名时,可用的this指针来区分
- 在类的非静态成员函数中,返回对象本身,可使用return *this
-
#include
using namespace std;
#include
class person
{
public:
person(int age)
{
//this指针指向对象成员函数所属的对象
this->age = age;
}
person& personaddage(person &p)//用person引用的方式返回,如果以值的形式返回,会创建一个新的对象
{
this->age += p.age;
//this 指向p2指针,而*this指向的就是p2这个对象本体
return *this;
}
int age;
};
//解决名称冲突
void test01()
{
person p1(18);
cout <<"p1的年龄为:" << p1.age << endl;
}
//返回对象本身
void test02()
{
person p2(10);
person p3(20);
//链式编程思想
p3.personaddage(p2).personaddage(p2);
cout << "p3的年龄为:" << p3.age << endl;
}
int main()
{
test01();
test02();
system("pause");
return 0;
}
三.空指针访问成员函数
#include
using namespace std;
#include
class person
{
public:
void showclassname()
{
cout << "this is person class" << endl;
}
void showpersonage()
{
//加上这个代码,就可以预防破坏,别人传入空指针
if (this == NULL)
{
return;
}
//报错原因是传入的指针为空 this->m_age 中this指向是空的
cout << "age=" << m_age << endl;//在对象属性前默认加this指针
}
int m_age;
};
void test01()
{
person* p=NULL;
p->showclassname();
p->showpersonage();
}
void test02()
{
}
int main()
{
test01();
//test02();
system("pause");
return 0;
}
四.const修饰成员函数
常函数
- 成员函数后加const后我们称这个函数为常函数
- 常函数内不可以修改成员属性
- 成员属性声明时关键字mutable后,在函数中依然可以修改
常对象
- 声明对象前加const称该对象为常对象
- 常对象只能调用常函数
- 类内对象成员和成员函数分开储存
- 只有非静态成员变量才属于类的对象上
- 非静态成员变量属于类的对象上
- 静态成员变量不属于类对象上
- 非静态成员函数不属于类对象上
- 静态成员函数不属于类对象上
- 空对象占用内存空间为1,c++编译器会给每个空对象分配一个字节的空间,是为了区分对象占内存的位置,每个空对象也有一个独一无二的内存地址
- this指针是隐含每一个非静态成员函数内的一种指针
- this指针指向被调用的成员函数所属的对象
- this指针不需要定义,直接使用即可
- 当形参和成员变量同名时,可用的this指针来区分
- 在类的非静态成员函数中,返回对象本身,可使用return *this
-
#include
using namespace std; #include class person { public: person(int age) { //this指针指向对象成员函数所属的对象 this->age = age; } person& personaddage(person &p)//用person引用的方式返回,如果以值的形式返回,会创建一个新的对象 { this->age += p.age; //this 指向p2指针,而*this指向的就是p2这个对象本体 return *this; } int age; }; //解决名称冲突 void test01() { person p1(18); cout <<"p1的年龄为:" << p1.age << endl; } //返回对象本身 void test02() { person p2(10); person p3(20); //链式编程思想 p3.personaddage(p2).personaddage(p2); cout << "p3的年龄为:" << p3.age << endl; } int main() { test01(); test02(); system("pause"); return 0; }
#include四.const修饰成员函数 常函数using namespace std; #include class person { public: void showclassname() { cout << "this is person class" << endl; } void showpersonage() { //加上这个代码,就可以预防破坏,别人传入空指针 if (this == NULL) { return; } //报错原因是传入的指针为空 this->m_age 中this指向是空的 cout << "age=" << m_age << endl;//在对象属性前默认加this指针 } int m_age; }; void test01() { person* p=NULL; p->showclassname(); p->showpersonage(); } void test02() { } int main() { test01(); //test02(); system("pause"); return 0; }
- 成员函数后加const后我们称这个函数为常函数
- 常函数内不可以修改成员属性
- 成员属性声明时关键字mutable后,在函数中依然可以修改
- 声明对象前加const称该对象为常对象
- 常对象只能调用常函数



