4.3.1成员变量和成员函数分开存储
1、成员变量与成员函数分开存储;
2、只有非静态成员变量在类上
3、当一个类中没有成员变量和成员函数时,仍然占一个字节的内存空间,目的是区分不同的空类
4.3.2this指针概念
#include<iostream>
#include<string>
using namespace std;
//class Person {
// int a;//非静态成员变量不属于类上
// static int b;//静态成员变量属于类
// void fun();//非静态成员函数不属于类
// static void fun1();//静态成员函数不属于类;
//
//};
class Person
{
public:
int age;
Person(int age)
{
//age = age;//形参与成员变量名称相同的时候,名称冲突赋值出错;
//this指针用来解决名称冲突问题;
this->age = age;
}
//注意这里要以引用的方式返回,才能一直返回P1本身;若以值的方式返回,
//则每次都会在另一个内存创建一个和传入相同的对象,不能改动P1原本的值;
Person& Personaddage(Person& P)
{
this->age += P.age;
return *this;
}
};
void test01()
{
Person P(18);
cout << "P年龄:" << P.age << endl;
}
void test02()
{
Person P1(10);
Person P2(20);
//链式编程的思想:可以不断的返回本身并且追加操作;
P1.Personaddage(P2).Personaddage(P2).Personaddage(P2).Personaddage(P2).Personaddage(P2);
cout << "P1年龄:" <<P1.age<< endl;
}
int main()
{
test02();
system("pause");
return 0;
}
4.3.3空指针访问成员函数
#include<iostream>
#include<string>
#include"point.h"
#include"Circle.h"
using namespace std;
//class Person {
// int a;//非静态成员变量不属于类上
// static int b;//静态成员变量属于类
// void fun();//非静态成员函数不属于类
// static void fun1();//静态成员函数不属于类;
//
//};
class Person
{
public:
void showname()
{
cout << "打印名称" << endl;
}
void showage()
{
if (this == NULL)//加判断来增强代码的健壮性,当指针为NULL时,return不返回任何值
{
return;
}
cout << "年龄:" << m_age << endl;//相当于this->m_age:当this为NULL时,不能访问成员变量
}
int m_age;
};
void test01()
{
Person *P=NULL;
P->showage();
}
int main()
{
test01();
system("pause");
return 0;
}
4.3.4const修饰成员函数
#include<iostream>
#include<string>
#include"point.h"
#include"Circle.h"
using namespace std;
class Person
{
public:
void showage()const//加const的成员函数被称为常函数
{
b = 90;
//m_age = 100;//成员函数后面加指针修饰的是this,故此时this指向的值也不能改变
//系统默认是this->m_age=100;
//this=NULL;//错误写法,this本质为指针常量。即指针的指向不能修改;Person*const this
//若想让指针指向的值也不能修改,要在前面加一个const修饰变为const Person*const this,即在函数的后面加const变为常函数
}
void fun()
{
}
int m_age;
mutable int b;//mutable关键字可以使得常函数改变该成员变量;
};
void test01()
{
Person p;
}
void test02()
{
const Person P;
//P.m_age = 10;
P.b = 100;//常对象只能访问mutable修饰的成员变量;
//P.fun();//常对象只能调用常函数
}
int main()
{
test02();
system("pause");
return 0;
}