类对象作为类成员
当其他类对象作为本类的成员的时候 构造函数先构造类对象 再构造自身
#include<iostream>
using namespace std;
class Phone
{
public:
string m_name;
Phone(string name)
{
cout << "Phone构造函数的调用" << endl;
m_name = name;
}
~Phone()
{
cout << "Phone析构函数的调用" << endl;
}
};
class Person
{
public:
Phone m_phone;
int m_age;
int m_height;
Person(int age, int height, string name): m_age(age), m_height(height), m_phone(name)
{
cout << "Person有参构造函数的调用" << endl;
}
~Person()
{
cout << "Person析构函数的调用" << endl;
}
};
void test()
{
Person p1(10 ,20, "小米");
}
int main()
{
test();
}
静态成员和静态成员函数 `
#include<iostream>
using namespace std;
class Person
{
public:
static int m_a;
int m_b;
static void func()
{
m_a = 10;
// m_b = 20;错误 静态成员函数只可以访问静态成员变量 不能访问非静态成员变量
cout << "func静态成员函数的调用" << endl;
}
};
void test()
{
// 1 通过对象俩进行访问
Person p1;
p1.func();
// 2 通过类名来进行访问
Person::func();
}
int main()
{
test();
}
类里面关于成员函数和成员变量的存储
#include<iostream>
using namespace std;
// 成员变量和成员函数是分开存储的
class Person
{
public:
static int m_a; // 非静态成员变量是在类的对象上的
int m_b; // 静态成员变量是没有在类的对象上的
static void func() // // 静态成员函数是没有在类的对象上的
{
}
void func1() // 非静态成员函数是没有在类的对象上的
{
}
};
void test()
{
Person p1;
cout << "p1占的字节数为:" << sizeof(p1) << endl;
}
int main()
{
test();
}
// 输出的结果为4 空对象占用的子节数为去 编译器会给每个空对象分配一个字节数 也就是每个空对象都会有一个独一无二的地址
this指针的概念
#include<iostream>
using namespace std;
// 成员变量和成员函数是分开存储的
class Person
{
public:
// 当形参和成员变量同名的时候 可以使用this指针来区分
int age;
Person(int age)
{
this->age = age;
}
Person& PersonAdd(Person& p) // 要返回本体 要用引用的方式返回 如果直接是Person的方式返回 则是一个浅拷贝 会重新创建一个对象 而不再是p2本身
{
age += p.age;
return *this; // this指向的是p2的指针 而*this指向的就是p2对象本身
}
};
void test()
{
Person p1(10);
Person p2(10);
p2.PersonAdd(p1).PersonAdd(p1).PersonAdd(p1);
cout << "这个时候p2的年龄是: " << p2.age << endl;
}
int main()
{
test();
}
空指针访问成员函数
#include<iostream>
using namespace std;
class Person
{
public:
int m_age;
void show()
{
// if这个操作就可以保持代码的健壮性
if (this == NULL)
{
return;
}
cout << "age= " << this->m_age << endl; // 这个如果前面不加If 则报错 原因是因为传入的是空指针
}
};
void test()
{
Person * p1 = NULL;
p1->show();
}
int main()
{
test();
}
const修饰成员函数
#include<iostream>
using namespace std;
class Person
{
public:
void show() const // 在成员函数后面加const 就是常函数了 修饰的是this 指针 让指针指向的值也不可以修改
{
m_a = 29;
}
int m_age;
mutable int m_a; // 特殊变量 即使在常函数中也可以修改它的值
};
void test()
{
const Person p1; // 在对象前面加const 变为常对象
//p1.m_age = 10 则普通的成员变量也不可以修改
p1.m_a = 20; // m_a是特殊变量 在常对象下也可以修改
// 常对象只能调用常函数 不能调用普通成员函数
p1.show();
}
int main()
{
test();
}