1、成员变量成员函数分开存储
#include<iostream>
#include<string>
using namespace std;
class Person
{
int m_name;//非静态成员属于类对象上。,占用内存
static int m_b; //静态成员变量不属于类对象上,访问内存是发现不占内存
void func(){}//非静态成员函数也不占内存,不属于类的对象上
};
void test01()
{
Person p;
cout<<"the size of p is:"<<sizeof(p)<<endl;
}
int main()
{
test01();
return 0;
}
二、this指针
#include<iostream>
#include<string>
using namespace std;
//this指针隐含在每一个非静态成员函数内,不需要定义直接使用
//作用:1、解决名称冲突;2、返回对象本身(*this)
class Person
{
public:
Person(int age)
{
this->age = age;//this指针指向被调用的成员函数所属的对象
}
int age;
};
void test01()
{
Person p1(20);
}
int main()
{
test01();
return 0;
}
三、const修饰成员函数
#include<iostream>
#include<string>
using namespace std;
class Person
{
public:
void showPerson() const
{
this->m_a = 100;//加了const后,指针指向的值不能修改,此处会报错!
}
int m_a;
};
void test01()
{
Person p;
p.showPerson();
}
void test01()
{
const Person p;//对象前加了const后,变为常对象,其值不能被修改
p.m_a = 100;//会报错
}
int main()
{
test01();
return 0;
}