学习目标:
学习内容:
1.成员变量和成员函数分开存储
在c++中,类内的成员函数和成员变量是分开存储的。只有非静态变量才属于类的对象。
我们通常使用sizeof
来计算类的储存空间。当类的对象为空的时候,内存空间默认为1,(c++编译器会给每个空对象也分配一个字节空间,是为了区分空字节的位置,每个空对象也有唯一的一个内存地址)。
#include<iostream>
using namespace std;
class Person
{
//空对象
};
void test()
{
//1.通过对象来访问
Person p;
cout << "the size of p " << sizeof(p) << endl;
}
int main()
{
test();
system("pause");
return 0;
}
一个整型的非静态变量,所占用类的空间为4。静态成员变量、非静态成员函数、静态成员函数都不属于类的对象,不占用类的空间
#include<iostream>
using namespace std;
class Person
{
int m_A;//非静态成员变量 属于类的对象上
static int m_B; //静态成员变量,不属于类的对象上
void func() {};//非静态成员函数 不属于类的对象上
static void func1() {}; //静态成员函数 不属于类对象上
};
int Person::m_B;
void test()
{
//1.通过对象来访问
Person p;
cout << "the size of p " << sizeof(p) << endl;
}
int main()
{
test();
system("pause");
return 0;
}
2.this指针
this指针是由C++提供的特殊对象指针,this指针指向被调用成员函数所属对象。this指针是隐含每个非静态成员函数内的一种指针,不需要定义,直接使用即可。this指针的用途:
- 当形参和成员变量同名时,可以用this指针来区分;
- 在类的非静态成员函数中返回类本身,可使用
return *this
;
2.1 this指针区分形参和成员变量(属性)
//解决同名冲突
#include<iostream>
using namespace std;
class Person
{
public:
Person(int age)
{
this ->age = age;
}
int age;
};
void test()
{
//1.通过对象来访问
Person p(18);
cout << "the age is " << p.age << endl;
}
int main()
{
test();
system("pause");
return 0;
}
2.2 类的非静态成员函数中返回类本身,可使用 return *this
#include<iostream>
using namespace std;
class person
{
public:
person(int age)
{
this->age = age;
}
//链式编程思想
person& personaddage(person& p) //返回类的引用(类名&)
{
this->age += p.age;
return *this;
}
int age;
};
void test()
{
person p1(10);
person p2(10);
p2.personaddage(p1).personaddage(p1).personaddage(p1);
cout << "p2的年龄为:" << p2.age << endl;
}
int main()
{
test();
system("pause");
return 0;
}
3.空指针访问成员函数
在一个类中,成员属性默认为是由this指针指向的,当有一个空指针去指向属性时会报错。
错误示例
此时我们加上一段代码,判断this
是否为空,若为空直接退出。
正确示例
//空指针调用成员函数
#include<iostream>
using namespace std;
class Person
{
public:
void showClassName()
{
cout << "this is Person class" << endl;
}
void showPeronName()
{
if (this == NULL)
{
return;
}
cout << "age = " << m_Age << endl;
}
int m_Age;
};
void test()
{
Person* p = NULL;
p->showClassName();
p->showPeronName();
}
int main()
{
test();
system("pause");
return 0;
}
4.const修饰成员函数
4.1常函数
- 成员函数后加const,称为常函数;
- 在常函数内不可以改变成员属性的值;
- 若想在常函数内的值,要在成员变量定义时加上关键字
mutable
//const修饰成员函数
#include<iostream>
using namespace std;
class Person
{
public:
void showPerson() const
{
m_A = 100;
cout << "m_A = " << m_A << endl;
}
mutable int m_A;
};
int main()
{
Person p;
p.showPerson();
system("pause");
return 0;
}
4.2 常对象
- 成员对象前加上const,称其为常对象;
- 常对象只能调用常函数;
//const修饰成员函数
#include<iostream>
using namespace std;
class Person
{
public:
void showPerson() const
{
m_A = 100;
cout << "m_A = " << m_A << endl;
}
mutable int m_A;
};
int main()
{
const Person p;
p.showPerson();
system("pause");
return 0;
}