成员变量和成员函数存储的问题
#include <iostream>
#include <stdio.h>
using namespace std;
//在C++中,类内的成员变量和成员函数分开存储
//只有非静态成员变量才属于类的对象上
class Person{
int m_a;//只有非静态成员变量才属于类的对象,才会分配空间
static int m_b;
void func(){
}
static void m_func(){
}
};
int Person::m_b=0;
//当为空对象时,编译器会分配一个内存空间,区分空对象占内存的位置
//每个空对象也应该有一个独一无二的位置
void test01(){
Person a;
cout <<sizeof(a);
}
int main(){
test01();
return 0;
}
this指针的用途
#include <iostream>
#include <stdio.h>
using namespace std;
//编码规范:类属性都加上m_
//this指针的用途:
//当形参和成员变量同名时,可用this指针来区分
//在类的非静态成员函数中返回对象本身,可使用return *this
class Person {
public:
Person(int age) {
this->age = age;
}
int age;
//引用返回本体
Person& PersonAddPerson(Person& a)
{
age += a.age;
//返回对象本身
return *this;
}
};
void test01() {
Person p1(10);
Person p2(10);
//实现链式编程
p1.PersonAddPerson(p2).PersonAddPerson(p2);
cout << p1.age;
}
int main() {
test01();
return 0;
}
空指针访问成员函数的问题
#include <iostream>
#include <stdio.h>
using namespace std;
//空指针访问成员函数,应该加以判断增加健壮性
class Person {
public:
void showclass() {
cout << "this is Person class" << endl;
}
void showAge() {
if (this == nullptr) return;
cout << m_Age;
}
int m_Age;
};
void test01() {
Person* p = nullptr;
p->showclass();
p->showAge();
}
int main() {
test01();
return 0;
}
常对象和常成员函数
#include <iostream>
#include <stdio.h>
using namespace std;
//const 修饰成员函数 和修饰对象
class Person {
public:
Person() {
m_a = 100;
m_b = 100;
}
//首先 this指针的本质是一个指针常量 ,它的指向不能够改变
//const 修饰成员函数之后,表示this指针是一个常量指针,其指向的值也不能够修改
void showPerson() const
{
//m_a = 100;不可修改
m_b = 100;
//this =NULL 错误,this指针的本质
}
void func() {
}
int m_a;
mutable int m_b;//如果想要在const函数修改它,加上关键字mutable
};
void test01() {
Person p;
p.showPerson();
}
void test02() {
const Person p;//在对象前加const ,变成常对象
p.m_b = 100;
p.showPerson();
//常对象只能调用常函数,普通函数中可以修改变量的值
//p.func();
}
int main() {
test01();
test02();
return 0;
}