4 类和对象
时间:2023-10-16 20:07 作者:wen 分类: C++
[toc]
类和对象
C++面向对象的三大特性为:封装、继承、多态
C++认为万事万物皆是对象,对象上有其属性和行为
列如:
人可以作为对象,属性有名称、年龄、身高、体重...,行为有走、跑、吃饭、唱歌
具有相同性质的对象,我们可以抽象称为类,人属于人类
封装
封装的意义
封装是C++面向对象三大特性之一
封装的意义:
- 将属性和行为作为一个整体,表现生活中的事物
- 将属性和行为加以权限控制
封装的意义一:
- 在设计类的时候,属性和行为写在一起,表现事物
语法:class 类名{ 访问权限:属性/行为}
示例:
#include <iostream>
using namespace std;
// 设计一个圆类, 并求周长
// 圆周长公式: 2 * PI * 半径
class Circle
{
const double PI = 3.1415926;
public:
// 属性
int m_r;
// 行为
double perimeter()
{
return 2 * PI * m_r;
}
};
int main()
{
// 实例化(通过一个类,创建一个对象的过程)
Circle c1;
c1.m_r = 10;
cout << "周长为: " << c1.perimeter() << endl;
system("pause");
return 0;
}
示例2:
#include <iostream>
using namespace std;
//设计一个学生类,属性有姓名和学号,可以给姓名和学号赋值,可以显示学生的姓名和学号
//学生类
class Student
{
public:
string m_name;
int m_id;
void showInfo()
{
cout << "姓名: " << m_name << " 学号为: " << m_id << endl;
}
};
int main()
{
Student s1;
s1.m_name = "张三";
s1.m_id = 1234;
s1.showInfo();
system("pause");
return 0;
}
封装的意义二:
- 类在设计时,可以把属性和行为放在不同的权限下,加以控制
- 访问权限有三种:
- public 公共权限
- protected 保护权限
- private 私有权限
示例:
#include <iostream>
using namespace std;
// 访问权限
// 1. 公有权限 public 成员 类内可以访问 类外可以访问
// 2. 保护权限 protected 成员 类内可以访问 类外不可以访问 子类可以访问
// 3. 私有权限 private 成员 类内可以访问 类外不可以访问 子类不可以访问
class Person
{
public:
string m_name;//姓名
protected:
string m_car;//车
private:
int m_password;//银行卡密码
public:
void func()
{
m_name = "张三";
m_car = "拖拉机";
m_password = 123456;
cout << m_name << "\t" << m_car << "\t" << m_password << endl;
}
};
int main()
{
Person p1;
p1.m_name = "李四";
//p1.m_car = "宝马"; // 类外不可访问
//p1.m_password = "111222"; // 类外不可访问
p1.func();
system("pause");
return 0;
}
struct和class区别
在C++中struct和class唯一的区别在于默认的访问权限不同
区别:
- struct默认权限为公共
- class默认权限为私有
示例:
#include <iostream>
using namespace std;
class C1
{
int m_A; // 默认权限 私有
};
struct C2
{
int m_A; // 默认权限 公共
};
int main()
{
C1 c1;
c1.m_A = 10; // 类外不能访问
C2 c2;
c2.m_A = 20;
system("pause");
return 0;
}
成员属性设置为私有
优点1: 将所有成员属性设置为私有,可以自己控制读写权限
优点2: 对于写权限, 我们可以检测数据的有效性
示例:
#include <iostream>
using namespace std;
class Person
{
// 成员属性设置为私有
string m_name; // 可读, 可写
int m_age = 0; // 可读
public:
void setName(string name)
{
m_name = name;
}
string getName()
{
return m_name;
}
int getAge()
{
return m_age;
}
void setAge(int age)
{
if (age > 0 && age < 150)
{
m_age = age;
}
else {
cout << "年龄不合法" << endl;
return;
}
}
};
int main()
{
Person p;
p.setName("张三");
cout << p.getName() << endl;
p.setAge(18);
cout << p.getAge() << endl;
system("pause");
return 0;
}
案例1:设计立方体类
设计立方体类(Cube)
求出立方体的面积和体积
分别用全局函数和成员函数判断两个立方体是否相等
示例:
#include <iostream>
using namespace std;
class Cube
{
public:
double m_L;//长
double m_W;//宽
double m_H;//高
// 体积
double volume()
{
return m_L * m_W * m_H;
}
// 面积
double area()
{
return 2 * m_L * m_W + 2 * m_L * m_H + 2 * m_W * m_H;
}
bool isSame(Cube& c)
{
if (m_L == c.m_L && m_W == c.m_W && m_H == c.m_H)
{
return true;
}
else {
return false;
}
}
};
bool isSame(Cube& c1,Cube& c2)
{
if (c1.m_L == c2.m_L && c1.m_W == c2.m_W && c1.m_H == c2.m_H)
{
return true;
}
else {
return false;
}
}
int main()
{
Cube c;
c.m_W = 10;
c.m_L = 10;
c.m_H = 30;
cout << "长方体的面积: " << c.area() << endl;
cout << "长方体的体积: " << c.volume() << endl;
// 创建第二个立方体
Cube c2;
c2.m_W = 11;
c2.m_L = 10;
c2.m_H = 30;
//全局函数判断
cout << isSame(c, c2) << endl;
//成员函数判断
cout << c.isSame(c2) << endl;
system("pause");
return 0;
}
案例2:点和圆的关系
设计一个圆形类(Circle),和一个点类(Point),计算点和圆的关系
#include <iostream>
using namespace std;
class Point
{
public:
double x;
double y;
};
class Circle
{
double PI = 3.1415926;
public:
double m_r;
Point m_center;
double len(Point& p)
{
return sqrt(pow(m_center.x - p.x, 2) + pow(m_center.y - p.y, 2));
}
};
int main()
{
Circle c;
Point p1;
p1.x = 0;
p1.y = 0;
c.m_center = p1;
c.m_r = 1;
Point p2;
p2.x = 0.4359;
p2.y = 0.9;
double len = c.len(p2);
if (len > c.m_r)
{
cout << "在圆外" << endl;
}
else if(len == c.m_r) {
cout << "在圆上" << endl;
}
else {
cout << "在圆内" << endl;
}
system("pause");
return 0;
}
对象的初始化和清理
- 在生活中我们买的电子产品基本都会有出厂设置,在某一天我们不用的时候,也会删除一些自己信息数据保证安全。
- C++中的面向对象来源于生活,每个对象也都会有初始设置以及兑现销毁前的清理数据的设置。
构造函数和析构函数
对象的初始化和清理也是两个非常重要的安全问题。
- 一个对象或者变量没有初始状态,对其使用后果是未知。
- 同样的使用完一个对象或变量,没有及时清理,也会造成一定的安全问题。
C++利用构造函数和析构函数解决上述问题,这两个函数将会被编译器自动调用,完成对象初始化和清理工作。
对象的初始化和清理工作是编译器强制要我们做的事情,因此如果我们不提供构造和析构,编译器会提供
编译器提供的构造函数和析构函数是空实现。
- 构造函数:主要作用在于创建对象时为对象的成员属性赋值,构造函数由编译器自动调用,无需手动调用。
- 析构函数:主要作用在于对象销毁前系统自动调用。执行一些清理工作。
构造函数语法:类名(){}
- 构造函数,没有返回值也不写void。
- 函数名与类名相同。
- 构造函数可以有参数,因此可以发生重载。
- 程序在调用对象时候会自动调用构造函数,无需手动调用,而且只会调用一次。
析构函数:~类名(){}
- 析构函数没有返回值,也不写void
- 函数名称与类名相同,在名称前加上符号 ~
- 析构函数不可以有参数,因此不可能发生重载。
- 程序在对象销毁前会自动调用析构函数,无需手动调用,而且只会调用一次。
#include <iostream>
using namespace std;
// 对象的初始化和清理
class Person
{
public:
// 1. 构造函数
Person()
{
cout << "构造函数调用" << endl;
}
// 2. 析构函数
~Person()
{
cout << "析构函数调用" << endl;
}
};
void test()
{
Person p;
}
int main()
{
test();
system("pause");
return 0;
}
构造函数的分类及调用
两种分类方式:
- 按参数分为:有参构造和无参构造
- 按类型分为:普通构造和拷贝构造
三种调用方式:
- 括号法
- 显示法
- 隐士转换法
#include <iostream>
using namespace std;
class Person
{
public:
string m_name;
// 1. 无参构造(默认构造)
Person()
{
cout << "构造函数调用" << endl;
}
// 2. 有参构造
Person(string name)
{
m_name = name;
cout << "有参构造函数调用" << endl;
}
// 3. 拷贝构造
Person(const Person& p)
{
// 将传入的所以属性,拷贝到我的身上
m_name = p.m_name;
cout << "拷贝构造函数调用" << endl;
}
// 析构函数
~Person()
{
cout << "析构函数调用" << endl;
}
};
void test()
{
// 1. 括号法
Person p; // 默认构造函数调用
Person p1("张三"); //有参构造函数
Person p2(p1); // 拷贝构造
//cout << p2.m_name << endl;
// 注意事项
// 调用默认构造函数时,不要加()
// 因为下面这行代码,编译器会认为是函数的声明,不会认为在创建对象
/*Person p0();
void func();*/
// 2. 显示法
Person p3 = Person("李四");
Person p4 = Person(p3);
//Person("李四"); //匿名对象 特点:当前行执行结束后,系统会立即回收匿名对象
// 注意事项
// 不要利用拷贝构造函数,初始化匿名对象,编译器会认为 Person(p4) === Person p4;
//Person(p4);
// 3. 隐士转换法
Person p5 = string("王五"); //相当于写了 Person p5 = Person("王五")
Person p6 = p5; // 拷贝构造 Person p6 = Person(p5)
}
int main()
{
test();
system("pause");
return 0;
}
拷贝构造函数调用时机
C++中拷贝构造函数调用时机通常有三种情况:
- 使用一个已经创建完毕的对象来初始化一个新对象。
- 值传递的方式给函数参数传值。
- 以值方式返回局部对象。(在C++11中被优化了)
示例:
#include <iostream>
using namespace std;
class Person
{
public:
string m_name;
// 1. 无参构造(默认构造)
Person()
{
cout << "构造函数调用" << endl;
}
// 2. 有参构造
Person(string name)
{
m_name = name;
cout << "有参构造函数调用" << endl;
}
// 3. 拷贝构造
Person(const Person& p)
{
// 将传入的所以属性,拷贝到我的身上
m_name = p.m_name;
cout << "拷贝构造函数调用" << endl;
}
// 析构函数
~Person()
{
cout << "析构函数调用" << endl;
}
};
// 1. 使用一个已经创建完毕的对象来初始化一个新对象
void testA()
{
Person p1 = (string)"李四";
Person p2(p1);
cout << p2.m_name << endl;
}
// 2. 值传递的方式给函数参数传值
void doWork(Person p)
{
}
void testB()
{
Person p1;
doWork(p1);
}
// 3. 值方式返回局部对象
Person doWork2()
{
Person p1;
cout << & p1 << endl;
return p1;
}
void testC()
{
Person p = doWork2();
cout << &p << endl;
}
int main()
{
//在 testC 中,doWork2 函数返回一个 Person 对象,但编译器通常会进行优化以避免不必要的拷贝构造。
//在这种情况下,编译器可能会直接将 p1 对象移动到 p 对象中,而不是创建 p 的副本。这是C++11引入的移动语义的一种应用。
//所以,在 testC 中,虽然涉及返回局部对象,但实际上没有发生拷贝构造,而是发生了移动构造或优化操作,以提高性能。
testC();
system("pause");
return 0;
}
构造函数调用规则
默认情况下,C++编译器至少给一个类添加三个函数。
- 默认构造函数(无参,函数体为空)
- 默认析构函数(无参,函数体为空)
- 默认拷贝构造函数,对属性进行值拷贝
构造函数调用规则如下:
- 如果用户定义有参构造函数,C++不再提供默认无参构造,但是会提供默认拷贝构造。
- 如果用户定义拷贝构造函数,C++不会再提供其他构造函数。
示例:
#include <iostream>
using namespace std;
class Person
{
public:
int m_age;
// 1. 无参构造(默认构造)
Person()
{
cout << "无参构造函数调用" << endl;
}
// 2. 有参构造
Person(int age)
{
m_age = age;
cout << "有参构造函数调用" << endl;
}
// 3. 拷贝构造
Person(const Person& p)
{
// 将传入的所以属性,拷贝到我的身上
m_age = p.m_age;
cout << "拷贝构造函数调用" << endl;
}
// 析构函数
~Person()
{
cout << "析构函数调用" << endl;
}
};
// 验证系统的默认拷贝构造函数
void testA()
{
// 注释拷贝构造函数, 使用默认的拷贝构造函数
Person p;
p.m_age = 18;
Person p2(p);
cout << p2.m_age << endl;
}
// 验证如果提供有参构造函数,系统不在提供默认无参构造函数,但是依然提高拷贝构造函数
void testB()
{
// 注释无参构造函数
//Person p; // 直接报错
Person p(10);
Person p2(p);
cout << p2.m_age << endl;
}
// 用户定义拷贝构造函数,C++不会再提供其他构造函数
void testC()
{
// 注释无参构造和有参构造
//Person p1; // // 直接报错
}
int main()
{
//testA();
//testB();
testC();
system("pause");
return 0;
}
深拷贝与浅拷贝
深浅拷贝是面试经典问题,也是常见的一个坑。
浅拷贝:简单的赋值拷贝操作。
深拷贝:在堆区重新申请空间进行拷贝操作。
示例:
#include <iostream>
using namespace std;
// 深拷贝和浅拷贝
class Person
{
public:
// 1. 无参构造(默认构造)
Person()
{
cout << "无参构造函数调用" << endl;
}
// 2. 有参构造
Person(int age, int height)
{
m_age = age;
m_height = new int(height);
cout << "有参构造函数调用" << endl;
}
// 3. 拷贝构造
Person(const Person& p)
{
// 将传入的所以属性,拷贝到我的身上
m_age = p.m_age;
//m_height = p.m_height // 编译器默认实现就是这行代码
m_height = new int(*p.m_height);
cout << "拷贝构造函数调用" << endl;
}
// 析构函数
~Person()
{
if (m_height != NULL)
{
delete m_height;
m_height = NULL;
}
cout << "析构函数调用" << endl;
}
int m_age;
int* m_height;
};
// 浅拷贝的问题是堆区的内存重复释放
void testA()
{
Person p1(18,160);
cout << "p1的年龄为:" << p1.m_age << " 身高为:" << *p1.m_height << endl;
Person p2(p1);
cout << "p2的年龄为:" << p2.m_age << " 身高为:" << *p2.m_height << endl;
}
int main()
{
testA();
system("pause");
return 0;
}
初始化列表
作用:C++提高了初始化列表语法,用来初始化属性
语法: 构造函数(): 属性1(值1),属性2(值2)...{}
示例:
#include <iostream>
using namespace std;
// 初始化列表
class Person
{
public:
// 传统初始化操作
/*Person(int a, int b, int c)
{
m_A = a;
m_B = b;
m_C = c;
}*/
//初始化列表初始化属性
Person(int a, int b, int c):m_A(a),m_B(b),m_C(c)
{}
int m_A;
int m_B;
int m_C;
};
void testA()
{
Person p(10,20,300);
cout << "m_A:" << p.m_A << endl;
cout << "m_B:" << p.m_B << endl;
cout << "m_C:" << p.m_C << endl;
}
int main()
{
testA();
system("pause");
return 0;
}
类对象作为类成员
C++类中的成员可以是另一个类的对象, 我们称该成员为对象成员
列如:
class A{}
class B
{
A a;
}
B类中有对象A作为成员,A为对象成员
那么当创建B对象是,A与B的构造和析构的顺序谁先谁后?
示例:
#include <iostream>
using namespace std;
// 类对象作为类成员
class Phone
{
public:
Phone(string name)
{
m_name = name;
cout << "Phone构造函数调用" << endl;
}
~Phone()
{
cout << "Phone析构函数调用" << endl;
}
// 手机品牌
string m_name;
};
class Person
{
public:
Person(string name, string pName) :m_Name(name),m_Phone(pName)
{
cout << "Person构造函数调用" << endl;
}
~Person()
{
cout << "Person析构函数调用" << endl;
}
// 姓名
string m_Name;
// 手机
Phone m_Phone;
};
// 当其它类对象作为本类的成员,先构造其它类的构造,然后在构造自身,析构的顺序与构造相反
void testA()
{
Person p("张三", "华为P60");
cout << p.m_Name << "拿着: " << p.m_Phone.m_name << endl;
}
int main()
{
testA();
system("pause");
return 0;
}
静态成员
静态成员就是子啊成员变量和成员函数前加上关键字static,称为静态成员
静态成员分为:
- 今天成员变量
- 所有对象共享一份数据
- 在编译阶段分配内存
- 类内声明,类外初始化
- 静态成员函数
- 所有对象共享同一个函数
- 静态成员函数只能访问静态成员变量
示例:静态成员变量
#include <iostream>
using namespace std;
//静态成员变量
class Person
{
public:
static int m_A;
private:
static int m_B;
};
// 1.访问访问
int Person::m_A = 100;
int Person::m_B = 200;
void testA()
{
Person p;
cout << p.m_A << endl;
Person p1;
p1.m_A = 200;
cout << p.m_A << endl;
cout << Person::m_A << endl;
}
int main()
{
testA();
system("pause");
return 0;
}
示例:静态成员函数
#include <iostream>
using namespace std;
//静态成员函数
class Person
{
public:
static void func()
{
m_A = 100; // 静态成员函数可以访问静态成员变量
//m_B = 200; // 静态成员函数不能访问非静态成员变量
cout << "static void func函数调用" << endl;
}
static int m_A;
int m_B;
};
void testA()
{
// 1.通过对象访问
Person p;
p.func();
// 2.通过类名访问
Person::func();
}
int main()
{
testA();
system("pause");
return 0;
}
C++对象模型和this指针
成员变量和成员函数分开存储
在C++中,类内的成员变量和成员函数分开存储
只有非静态成员变量才属于类的对象上
#include <iostream>
using namespace std;
class Person
{
public:
int m_A; // 非静态成员变量,属于类的对象上
static int m_B; // 静态成员变量,不属于类的对象上
void func() {} // 非静态成员函数,不属于类的对象上
static void funcA() {} // 静态成员函数,不属于类的对象上
};
void testA() {
Person p;
// 空对象占用内存空间为: 1
// size of p = 1
// C++编译器会给每个空对象也分配一个字节空间,是为了区分空对象占内存的位置
// 每个空对象也应该有一个独一无二的内存地址
cout << "size of p = " << sizeof(p) << endl;
}
void testB()
{
Person p;
// size of p = 4
cout << "size of p = " << sizeof(p) << endl;
}
int main()
{
//testA();
testB();
system("pause");
return 0;
}
this指针概念
通过上面我们知道在C++中成员变量和成员函数是分开存储的
每一个非静态成员函数只诞生一份函数实例,也就是说多个同类型的对象会共用一块代码
那么问题是:这一块代码是如何区分那个对象调用自己呢?
C++通过提供特殊的对象指针,this指针,解决上述问题。this指针指向被调用的成员函数所属的对象
this指针是隐含每一个非静态成员函数内的一种指针
this指针不需要定义,直接使用即可
this指针的用途:
- 当形参和成员变量同名是,可用this指针来区分
- 在类的非静态成员函数中返回对象本身,可使用
return *this
#include <iostream>
using namespace std;
class Person
{
public:
Person(int age) {
// 1.解决名称冲突
//this指针指向,把给调用的成员函数所属对象
this->age = age;
}
// 2.返回对象本身
Person& addAge(Person& p)
{
this->age += p.age;
return *this;
}
int age;
};
void testA() {
Person p(18);
cout << p.age << endl;
}
void testB() {
Person p1 = 18;
Person p2 = 10;
// 链式编程思想
p2.addAge(p1).addAge(p1);
cout << p2.age << endl;
}
int main()
{
testB();
system("pause");
return 0;
}
空指针访问成员函数
C++中空指针也是可以调用成员函数的,但是也要注意有没有用到this指针
如果用到this指针,需要加以判断保证代码的健壮性
示例:
#include <iostream>
using namespace std;
class Person
{
public:
void showClassName()
{
if (this == NULL)
{
return;
}
cout << "this is Person class" << endl;
}
void showPersonAge()
{
if (this == NULL)
{
return;
}
cout << "age = " << this->age << endl;
}
int age;
};
void testA() {
Person *p = NULL;
//cout << p->showClassName << endl;
//cout << p->showPersonAge << endl;
}
int main()
{
testA();
system("pause");
return 0;
}
const修饰成员函数
常函数:
- 成员函数后加const后我们称为这个函数为常函数
- 常函数内不可以修改成员属性
- 成员属性声明时加关键字mutable后,在常函数中依然可以修改
常对象:
- 声明对象前加const称该对象为常对象
- 常对象只能调用常函数
示例:
#include <iostream>
using namespace std;
class Person
{
public:
// 常函数
// this指针的本质是指针常量,指针的指向是不可修改的
//const Person * const this
// 在成员函数后面加const,修饰的是this指针,让指针指向的值也不可以修改
void showPerson() const
{
//m_A = 100; //不可以修改
this->m_B = 200;
}
void func()
{
m_A = 100;
cout << m_A << endl;
}
int m_A;
mutable int m_B; // 特殊变量,即使在常函数中,也可以修改这个值
};
void testA() {
Person p;
p.showPerson();
}
void testB() {
// 常对象
const Person p;
//p.m_A = 100;
p.m_B = 200;
// 常对象只能调用常函数
p.showPerson();
//p.func(); // 不可以调用
}
int main()
{
testB();
system("pause");
return 0;
}
友元
在生活中你的家有客厅(Pubilc),由你的卧室(Private)
客厅所有来的客人都可以进去,但是你的卧室是私有的,也就是说只有你能进去
但是呢,你也可以允许你的好基友进去。
在程序里,有些私有属性也想让类外特殊的一些函数或者类进行访问,就需要用到友元的技术
友元的目的就是让一个函数或者类 访问另一个类中私有成员
友元的关键字为 friend
友元的三种实现
- 全局函数做友元
- 类做友元
- 成员函数做友元
示例1:
#include <iostream>
using namespace std;
// 建筑物类
class Building
{
// goodGay全局函数是Building好朋友,可以访问Building中私有成员
friend void goodGay(Building& b);
public:
Building()
{
m_SittingRoom = "客厅";
m_BedRoom = "卧室";
}
public:
string m_SittingRoom; // 客厅
private:
string m_BedRoom; // 卧室
};
// 全局函数做友元
void goodGay(Building& building) {
cout << "好基友全局函数 正在访问:" << building.m_SittingRoom << endl;
cout << "好基友全局函数 正在访问:" << building.m_BedRoom << endl;
}
int main()
{
Building b;
goodGay(b);
system("pause");
return 0;
}
示例2:
#include <iostream>
using namespace std;
class Building
{
// GoodGay类是本类的好朋友可以访问私有属性
friend class GoodGay;
public:
Building()
{
m_SittingRoom = "客厅";
m_BedRoom = "卧室";
}
public:
string m_SittingRoom; // 客厅
private:
string m_BedRoom; // 卧室
};
class GoodGay
{
public :
void visit(); //参观函数 访问Building中的属性
Building* building;
public:
GoodGay();
};
// 类外协成员函数
GoodGay::GoodGay()
{
building = new Building;
}
void GoodGay::visit()
{
cout << "好基友类正在访问: " << building->m_SittingRoom << endl;
cout << "好基友类正在访问: " << building->m_BedRoom << endl;
}
// 类做为友元
void testA()
{
GoodGay gg;
gg.visit();
}
int main()
{
testA();
system("pause");
return 0;
}
示例3:
#include <iostream>
using namespace std;
class Building;
class GoodGay
{
public:
void visit(); //参观函数 访问Building中的属性
Building* building;
GoodGay();
};
class Building
{
// GoodGay类中的visit成员函数是本类的好朋友可以访问私有属性
friend void GoodGay::visit();
public:
Building()
{
m_SittingRoom = "客厅";
m_BedRoom = "卧室";
}
public:
string m_SittingRoom; // 客厅
private:
string m_BedRoom; // 卧室
};
// 类外协成员函数
GoodGay::GoodGay()
{
building = new Building;
}
void GoodGay::visit()
{
cout << "好基友类正在访问: " << building->m_SittingRoom << endl;
cout << "好基友类正在访问: " << building->m_BedRoom << endl;
}
// 成员函数做友元
void testA()
{
GoodGay gg;
gg.visit();
}
int main()
{
testA();
system("pause");
return 0;
}
运算符重载
运算符重载概念:对已有的运算符重新进行定义,赋予其另一种功能,以适应不同的数据类型
加号运算符重载
作用:实现两个自定义数据类型相加的运算
#include <iostream>
using namespace std;
//加号运算符重载
class Person
{
public:
int m_A;
int m_B;
// 成员函数重载本质调用
//Person p3 = p1.operator+(p2);
/*Person operator+(const Person& other) const
{
Person temp;
temp.m_A = this->m_A + other.m_A;
temp.m_B = this->m_B + other.m_B;
return temp;
}*/
};
// 通过全局函数重载+
// Person p3 = operator+(p1,p2);
Person operator+(const Person& p1, const Person& p2)
{
Person temp;
temp.m_A = p1.m_A + p2.m_A;
temp.m_B = p1.m_B + p2.m_B;
return temp;
}
Person operator+(const Person& p1, int num)
{
Person temp;
temp.m_A = p1.m_A + num;
temp.m_B = p1.m_B + num;
return temp;
}
void testA()
{
Person p1;
Person p2;
p1.m_A = 10;
p1.m_B = 10;
p2.m_A = 10;
p2.m_B = 10;
Person p3;
p3 = p1 + p2;
cout << p3.m_A << " " << p3.m_B << endl;
// 运算符重载也可以发生函数重载
Person p4;
p4 = p1 + 20;
cout << p4.m_A << " " << p4.m_B << endl;
}
int main()
{
testA();
system("pause");
return 0;
}
总结:对于内置的数据类型的表达式的运算符是不可能改变的
总结2:不要滥用运算符重载
左移运算符重载
作用:可以输出自定义数据类型
#include <iostream>
using namespace std;
//左移运算符重载
class Person
{
friend ostream& operator<<(ostream& cout, Person& p);
public:
Person() {
this->m_A = 10;
this->m_B = 10;
}
private:
//成员函数重载左移运算符
//p.operator<<(cout) 简化版本 p << cout
//不会利用成员函数重载<<运算符,因为无法实现cout在左侧
/*void operator<<(cout)
{
}*/
int m_A;
int m_B;
};
//只能利用全局函数重载左移运算符
// 本质 operator<<(cout,p) 简化 cout << p
ostream& operator<<(ostream& cout, Person& p)
{
cout << "m_A = " << p.m_A << " m_B = " << p.m_B;
return cout;
}
void testA()
{
Person p1;
cout << p1 << endl << p1 << endl << "hello world" << endl;;
}
int main()
{
testA();
system("pause");
return 0;
}
递增运算符重载
作用:通过重载递增运算符,实现自己的整型数据
#include <iostream>
using namespace std;
//重载递增运算符
class MyInteger
{
friend ostream& operator<<(ostream& cout, const MyInteger& myint);
public:
MyInteger()
{
m_Num = 0;
}
//重载++运算符 前置
MyInteger& operator++()
{
//先进行++运算
m_Num++;
//再将自身返回
return *this;
}
//重载++运算符 后置
//占位参数, 可以用于区分前置和后置递增
MyInteger operator++(int)
{
// 先 记录当时结果
MyInteger temp = *this;
// 后 递增
m_Num++;
// 最后将记录结果返回
return temp;
}
private:
int m_Num;
};
//重载左移运算符
ostream& operator<<(ostream& cout, const MyInteger& myint)
{
cout << myint.m_Num;
return cout;
}
void testA()
{
MyInteger myint;
cout << ++(++myint) << endl;
cout << myint << endl;
}
void testB()
{
MyInteger myint;
cout << myint++ << endl; // 后置递增
cout << myint << endl;
}
int main()
{
testB();
system("pause");
return 0;
}
赋值运算符重载
C++编译器至少给一个类添加4个函数
- 默认构造函数(无参,函数体为空)
- 默认析构函数(无参,函数体为空)
- 默认拷贝构造函数,对属实进行值拷贝
- 赋值运算符operator=,对属性进行值拷贝
如果类中有属性指向堆区,做赋值操作时也会出现深浅拷贝问题
示例:
#include <iostream>
using namespace std;
// 赋值运算符重载
class Person
{
public:
Person(int age)
{
m_Age = new int(age);
}
Person& operator=(Person& p)
{
//编译器提供浅拷贝
//m_Age = p.m_Age;
//先判断是否有属性在堆区, 如果有先释放干净,然后在深拷贝
if (m_Age != NULL)
{
delete m_Age;
m_Age = NULL;
}
// 深拷贝
m_Age = new int(*p.m_Age);
return *this;
}
int* m_Age;
~Person()
{
if (m_Age != NULL)
{
delete m_Age;
}
}
};
void testA()
{
Person p(18);
Person p2(20);
Person p3(10);
p2 = p = p3 ;
cout << "p 的年龄为: " << *p.m_Age << endl;
cout << "p 的年龄为: " << *p2.m_Age << endl;
}
int main()
{
testA();
system("pause");
return 0;
}
关系运算符重载
作用:重载关系运算符,可以让两个自定义类型对象进行对比操作
示例:
#include <iostream>
using namespace std;
// 比较运算符重载
class Person
{
public:
Person(string name,int age):m_Name(name),m_Age(age)
{
}
bool operator==(Person& p)
{
if (this->m_Name == p.m_Name && this->m_Age == p.m_Age)
{
return true;
}
return false;
}
bool operator!=(Person& p)
{
if (this->m_Name == p.m_Name && this->m_Age == p.m_Age)
{
return false;
}
return true;
}
string m_Name;
int m_Age;
};
void testA()
{
Person p1("Tom", 18);
Person p2("Tom", 18);
if (p1 == p2)
{
cout << "p1 和 p2 相等" << endl;
}
else {
cout << "p1 和 p2 不相等" << endl;
}
}
int main()
{
testA();
system("pause");
return 0;
}
函数调用运算符重载
- 函数调用运算符 () 也可以重载
- 由于重载使用的方式非常像函数的调用,因此称为仿函数
- 仿函数没有固定写法,非常灵活
示例:
#include <iostream>
using namespace std;
// 函数调用运算符重载
class MyPrint
{
public:
void operator()(string test)
{
cout << test << endl;
}
};
void testA()
{
MyPrint myPrint;
myPrint("hello world"); // 非常像函数调用,因此称为仿函数
}
int main()
{
testA();
system("pause");
return 0;
}
继承
继承是面向对象三大特性之一
继承的基本语法
例如我们看到很多网站中,都有公共的头部,公共的底部,甚至公共的左侧列表,只有中心内容不同
接下来我们分别利用普通写法和继承写法来实现网页中的内容,看一下继承存在的意义以及好出
语法:class 子类: 继承方式 父类
子类 也称为 派生类
父类 也称为 基类
普通实现:
#include <iostream>
using namespace std;
// 普通实现
class Java
{
public:
void header()
{
cout << "公共头部" << endl;
}
void footer()
{
cout << "公共底部" << endl;
}
void left()
{
cout << "公共左侧" << endl;
}
void content()
{
cout << "JAVA学科内容" << endl;
}
};
class PHP
{
public:
void header()
{
cout << "公共头部" << endl;
}
void footer()
{
cout << "公共底部" << endl;
}
void left()
{
cout << "公共左侧" << endl;
}
void content()
{
cout << "PHP学科内容" << endl;
}
};
void testA()
{
Java ja;
ja.header();
ja.footer();
ja.left();
ja.content();
PHP php;
php.header();
php.footer();
php.left();
php.content();
}
int main()
{
testA();
system("pause");
return 0;
}
继承实现:
#include <iostream>
using namespace std;
// 继承实现
class Commom
{
public:
void header()
{
cout << "公共头部" << endl;
}
void footer()
{
cout << "公共底部" << endl;
}
void left()
{
cout << "公共左侧" << endl;
}
};
class Java: public Commom
{
public:
void content()
{
cout << "JAVA学科内容" << endl;
}
};
class PHP: public Commom
{
public:
void content()
{
cout << "PHP学科内容" << endl;
}
};
void testA()
{
Java ja;
ja.header();
ja.footer();
ja.left();
ja.content();
PHP php;
php.header();
php.footer();
php.left();
php.content();
}
int main()
{
testA();
system("pause");
return 0;
}
继承方式
继承方式一共有三种:
- 公共继承 (父类私有属性不可访问, 其它权限属性之间继承)
- 保护继承 (父类私有属性不可访问, 其它权限属性放到保护权限)
- 私有继承 (父类私有属性不可访问, 其它权限属性放到私有权限)
示例:
#include <iostream>
using namespace std;
// 继承方式
class Base
{
public:
int m_A;
protected:
int m_B;
private:
int m_C;
};
class SonA : public Base
{
public :
void func()
{
m_A = 10; // 公共权限 可以访问
m_B = 10; // 保护权限 可以访问
//m_C = 10; // 私有权限 不可以访问
}
};
class SonB : protected Base
{
public:
void func()
{
// 父类公共成员和保护成员都变为保护成员
m_A = 10; // 保护权限 可以访问
m_B = 10; // 保护权限 可以访问
//m_C = 10; // 私有权限 不可以访问
}
};
class SonC : private Base
{
public:
void func()
{
// 父类公共成员和保护成员都变为私有成员
m_A = 10; // 私有权限 可以访问
m_B = 10; // 私有权限 可以访问
//m_C = 10; // 私有权限 不可以访问
}
};
class GrandSonC : public SonC
{
void func()
{
// 在孙子类中访问不到父类私有成员
}
};
void testA()
{
SonA sa;
sa.m_A = 100; // 内外 公共权限 可以访问
//sa.m_B = 100; // 内外 保护权限 不可以访问
}
void testB()
{
SonB sa;
//sa.m_A = 100; // 内外 保护权限 不可以访问
}
void testC()
{
SonC sa;
//sa.m_A = 100;// 内外 私有权限 不可以访问
}
int main()
{
testB();
system("pause");
return 0;
}
继承中的对象模型
问题:从父类继承过来的成员,那些属于子类对象中?
示例:
#include <iostream>
using namespace std;
class Base
{
public:
int m_A;
protected:
int m_B;
private:
int m_C;
};
class Son : public Base
{
public :
int m_D;
};
void testA()
{
// 在父类中所有非静态成员属性都会被子类继承下去
// 父类中私有成员属性是被编译器给隐藏了,因此是访问不到,但是确实被继承下去了
cout << "size of Son = " << sizeof(Son) << endl; // 16
}
int main()
{
testA();
system("pause");
return 0;
}
D:\Code\C++\basic\01_helloworld\01_helloworld>cl /d1 reportSingleClassLayoutSon 01_helloworld.cpp
用于 x86 的 Microsoft (R) C/C++ 优化编译器 19.36.32537 版
版权所有(C) Microsoft Corporation。保留所有权利。
01_helloworld.cpp
class Son size(16):
+---
0 | +--- (base class Base
0 | | m_A
4 | | m_B
8 | | m_C
| +---
12 | m_D
+---
继承中构造和析构顺序
子类继承父类后,当创建子类对象,也会调用父类的构造函数
问题:父类和子类的构造和析构顺序是谁先谁后?
示例:
#include <iostream>
using namespace std;
class Base
{
public:
Base()
{
cout << "Base 构造函数" << endl;
}
~Base()
{
cout << "Base 析构函数" << endl;
}
};
class Son : public Base
{
public:
Son()
{
cout << "Son 构造函数" << endl;
}
~Son()
{
cout << "Son 析构函数" << endl;
}
};
void testA()
{
Son s;
/*
Base 构造函数
Son 构造函数
Son 析构函数
Base 析构函数
*/
}
int main()
{
testA();
system("pause");
return 0;
}
总结:在继承中构造和析构的顺序为,先构造父类在构造子类,先析构子类再析构父类
继承同名成员处理方式
问题:当子类与父类出现同名的成员,如何通过子类对象,访问到子类或父类中同名的数据呢?
- 访问子类同名成员,直接访问即可
- 访问父类同名成员,需要加作用域
示例:
#include <iostream>
using namespace std;
class Base
{
public:
Base()
{
m_A = 100;
}
void func()
{
cout << "Base 成员函数" << endl;
}
void func(int a)
{
cout << "Base func(int a)" << endl;
}
int m_A;
};
class Son : public Base
{
public:
Son()
{
m_A = 200;
}
void func()
{
cout << "Son 成员函数" << endl;
}
int m_A;
};
// 同名成员属性
void testA()
{
Son s;
cout << "Son m_A = " << s.m_A << endl;
// 访问父类同名成员需要加作用域
cout << "Base m_A = " << s.Base::m_A << endl;
}
// 同名成员函数
void testB()
{
Son s;
s.func();
s.Base::func();
// 如果子类中出现和父类同名的成员函数,子类的同名成员会隐藏调父类所有同名成员函数
// 如果想访问到父类中隐藏的同名成员函数,需要加作用域
s.Base::func(100);
}
int main()
{
testB();
system("pause");
return 0;
}
子类可以直接访问父类的成员属性和函数
如果子类中出现和父类同名的成员函数,子类的同名成员会隐藏调父类所有同名成员函数
如果想访问到父类中隐藏的同名成员函数,需要加作用域
继承同名静态成员处理方式
问题:继承中同名的静态成员在子类对象上如何进行访问?
静态成员和非静态成员出现同名,处理方式一致
- 访问子类同名成员,直接访问即可
- 访问父类同名成员,需要加作用域
示例:
#include <iostream>
using namespace std;
class Base
{
public:
static void func()
{
cout << "Base 成员函数" << endl;
}
static void func(int a)
{
cout << "Base func(int a)" << endl;
}
static int m_A;
};
int Base::m_A = 100;
class Son : public Base
{
public:
static void func()
{
cout << "Son 成员函数" << endl;
}
static int m_A;
};
int Son::m_A = 200;
// 同名成员属性
void testA()
{
// 1. 通过对象访问属性
Son s;
cout << "Son m_A = " << s.m_A << endl;
// 访问父类同名成员需要加作用域
cout << "Base m_A = " << s.Base::m_A << endl;
// 2. 通过类名访问
cout << "Son m_A = " << Son::m_A << endl;
cout << "Base m_A = " << Son::Base::m_A << endl;
}
// 同名成员函数
void testB()
{
// 1. 通过对象访问属性
Son s;
s.func();
s.Base::func();
// 如果子类中出现和父类同名的成员函数,子类的同名成员会隐藏调父类所有同名成员函数
// 如果想访问到父类中隐藏的同名成员函数,需要加作用域
s.Base::func(100);
// 2. 通过类名访问
Son::func();
Son::Base::func();
}
int main()
{
testB();
system("pause");
return 0;
}
总结:同名静态成员处理方式和非静态处理方式一样,只不过有两种访问方式(通过对象 和 通过类名)
多继承语法
C++允许一个类继承多个类
语法:class 子类: 继承方式 父类1, 继承方式 父类2,...
多继承可能会引发父类中有同名成员出现,需要加作用域区分
C++实际开发中不建议用多继承
示例:
#include <iostream>
using namespace std;
class BaseA
{
public:
BaseA()
{
m_A = 100;
}
int m_A;
};
class BaseB
{
public:
BaseB()
{
m_A = 200;
}
int m_A;
};
// 子类 继承 BaseA, BaseB
class Son : public BaseA, public BaseB
{
public:
Son()
{
m_C = 300;
m_D = 400;
}
int m_C;
int m_D;
};
void testA()
{
Son s;
cout << "size of Son = " << sizeof(s) << endl;
// 父类中出现同名成员,需要加作用域区分
cout << s.BaseA::m_A << endl;
cout << s.BaseB::m_A << endl;
cout << s.m_C << endl;
cout << s.m_D << endl;
}
int main()
{
testA();
system("pause");
return 0;
}
D:\Code\C++\basic\01_helloworld\01_helloworld>cl /d1 reportSingleClassLayoutSon 01_helloworld.cpp
用于 x86 的 Microsoft (R) C/C++ 优化编译器 19.36.32537 版
版权所有(C) Microsoft Corporation。保留所有权利。
01_helloworld.cpp
class Son size(16):
+---
0 | +--- (base class BaseA)
0 | | m_A
| +---
4 | +--- (base class BaseB)
4 | | m_B
| +---
8 | m_C
12 | m_D
+---
多继承中如果父类中出现同名成员,需要加作用域区分
菱形继承
菱形继承概念:
- 两个派生类继承同一个基类
- 又有某个类同时继承两个派生类
- 这种继承被称为菱形继承,或者砖石继承
菱形继承问题:
- 羊继承了动物的数据,驼同样继承了动物的数据,当羊驼使用数据时,就会产生二义性。
- 羊驼继承自动物的数据继承了两份,其实我们应该清楚,这份数据我们只需要一份就可以。
可以利用虚继承:
语法:class 子类 : virtual 继承方式 父类 {}
示例:
#include <iostream>
using namespace std;
// 动物类
class Animal
{
public:
int m_Age;
};
//利用虚继承 解决菱形继承问题
// 继承之前 加上关键字 virtual 变为虚继承
// Animal称为 虚基类
// 羊类
class Sheep : virtual public Animal
{
};
// 驼类
class Tuo : virtual public Animal
{
};
// 羊驼类
class SheepTuo : public Sheep, public Tuo
{
};
void testA()
{
SheepTuo st;
st.Sheep::m_Age = 18;
st.Tuo::m_Age = 28;
// 当菱形继承,又两个父类拥有相同的数据,需要加作用域区分
cout << "st.Sheep::m_Age = " << st.Sheep::m_Age << endl;
cout << "st.Tuo::m_Age = " << st.Tuo::m_Age << endl;
//加上虚继承后
cout << "st.m_Age = " << st.m_Age << endl;
}
int main()
{
testA();
system("pause");
return 0;
}
多态
多态的基本概念
多态是面向对象三大特性之一
多态分为两类:
- 静态多态:函数重载 和 运算符重载属于静态多态,复用函数名
- 动态多态:派生类和虚函数实现运行时多态
静态多态和动态多态区别:
- 静态多态的函数地址早绑定 - 编译阶段确定函数地址
- 动态多态的函数地址晚绑定 - 运行阶段确定函数地址
示例:
#include <iostream>
using namespace std;
// 动物类
class Animal
{
public:
virtual void speak()
{
cout << "动物在说话" << endl;
}
};
// 猫类
class Cat : public Animal
{
public:
void speak()
{
cout << "小猫在说话" << endl;
}
};
// 执行说话的函数
// 地址早绑定, 在编译阶段确定函数地址
void doSpeak(Animal& animal) // Animal& animal = cat;
{
animal.speak();
}
void testA()
{
Cat cat;
doSpeak(cat);
}
int main()
{
testA();
system("pause");
return 0;
}
动态多态满足条件
- 有继承关系
- 子类要重写父类虚函数
动态多态使用:父类的指针或引用 执行子类对象
多态案例一:计算器类
案例描述:
分别利用普通写法和多态技术,设计实现两个操作数进行运算的计算器类
多态的有点:
- 代码组织结构清晰
- 可读性强
- 利于前期和后期的扩展以及维护
普通写法示例:
#include <iostream>
using namespace std;
// 普通写法
class Calculator
{
public:
int getResult(string oper)
{
if (oper == "+")
{
return m_NumA + m_NumB;
}
else if (oper == "-") {
return m_NumA - m_NumB;
}
else if (oper == "*") {
return m_NumA * m_NumB;
}
else if (oper == "/") {
return m_NumA / m_NumB;
}
}
int m_NumA;
int m_NumB;
};
void testA() {
Calculator c;
c.m_NumA = 10;
c.m_NumB = 10;
cout << c.getResult("+") << endl;
cout << c.getResult("-") << endl;
cout << c.getResult("*") << endl;
cout << c.getResult("/") << endl;
}
int main()
{
testA();
system("pause");
return 0;
}
多态写法示例:
#include <iostream>
using namespace std;
// 多态写法
class AbstractCalculator
{
public:
virtual int getResult()
{
return 0;
}
int m_NumA;
int m_NumB;
};
// 加法计算器类
class AddCalculator : public AbstractCalculator
{
public:
int getResult()
{
return m_NumA + m_NumB;
}
};
class SubCalculator : public AbstractCalculator
{
public:
int getResult()
{
return m_NumA - m_NumB;
}
};
class MulCalculator : public AbstractCalculator
{
public:
int getResult()
{
return m_NumA * m_NumB;
}
};
void testA() {
AbstractCalculator* abc = new AddCalculator;
abc->m_NumA = 10;
abc->m_NumB = 10;
cout << abc->getResult() << endl;
delete abc;
abc = new SubCalculator;
abc->m_NumA = 10;
abc->m_NumB = 10;
cout << abc->getResult() << endl;
delete abc;
abc = new MulCalculator;
abc->m_NumA = 10;
abc->m_NumB = 10;
cout << abc->getResult() << endl;
delete abc;
}
int main()
{
testA();
system("pause");
return 0;
}
纯虚数函数和抽象类
在多态中,通常父类中虚函数的实现是毫无意义的,主要都是调用子类重写的内容
因此可以将虚函数改为纯虚函数
纯虚函数语法:virtual 返回值类型 函数名(参数类别) = 0
当类中有纯虚函数,这个类也称为抽象类
抽象类特点:
- 无法实例化对象
- 子类必须重写抽象类中的纯虚函数,否则也属于抽象类
示例:
#include <iostream>
using namespace std;
// 抽象类 和 纯虚函数
class Base
{
public:
// 纯虚函数
// 只要有一个纯虚函数,这个类称为抽象类
virtual void func() = 0;
};
class Son : public Base
{
virtual void func()
{
cout << "Son func函数调用" << endl;
}
};
void testA() {
//Base b; 1. 无法实例化
//Son s; 2. 子类必须重写父类的纯虚函数,否则这个类也是抽象类
Base* b = new Son;
b->func();
}
int main()
{
testA();
system("pause");
return 0;
}
多态案例二:制作饮品
案例描述:
制作饮品的大致流程:煮水-冲泡-倒入杯中-加入辅料
利用多态技术实现本案例,提供抽象制作饮品基类,提供子类制作咖啡喝茶叶
#include <iostream>
using namespace std;
class Base
{
public:
// 煮水
virtual void zhuShui() = 0;
// 冲泡
virtual void chonPao() = 0;
// 倒入杯中
virtual void ruBeing() = 0;
// 加入辅料
virtual void jiaFuLiao() = 0;
};
class Caffe : public Base
{
public:
void zhuShui()
{
cout << "煮水" << endl;
}
void chonPao()
{
cout << "冲泡咖啡" << endl;
}
void ruBeing()
{
cout << "倒入杯中" << endl;
}
void jiaFuLiao()
{
cout << "加糖和牛奶" << endl;
}
};
class Tea : public Base
{
public:
void zhuShui()
{
cout << "煮水" << endl;
}
void chonPao()
{
cout << "冲泡茶叶" << endl;
}
void ruBeing()
{
cout << "倒入杯中" << endl;
}
void jiaFuLiao()
{
cout << "加柠檬" << endl;
}
};
void testA() {
Base* b = new Caffe;
b->zhuShui();
b->chonPao();
b->ruBeing();
b->jiaFuLiao();
b = new Tea;
b->zhuShui();
b->chonPao();
b->ruBeing();
b->jiaFuLiao();
delete b;
}
int main()
{
testA();
system("pause");
return 0;
}
虚析构和纯虚析构
多态使用时,如果子类中有属性开辟到堆区,那么父类指针在释放时无法调用到子类的析构代码
解决方式:将父类中的析构函数改为虚析构或者纯虚析构
虚析构和纯虚析构共性:
- 可以解决父类指针释放子类对象
- 都需要有具体的函数实现
虚析构和纯虚析构区别
- 如果是纯虚析构,该类属于抽象类,无法实例化对象
虚析构语法:virtual ~类名(){}
纯虚析构语法:virtual ~类名() = 0
#include <iostream>
using namespace std;
class Animal
{
public:
virtual void speak() = 0;
// 利用虚析构可以解决 父类指针释放子类对象时不干净问题
virtual ~Animal()
{
cout << "Animal析构函数" << endl;
}
// 纯虚析构 需要声明也需要实现
//virtual ~Animal() = 0;
};
//Animal::~Animal()
//{
// cout << "Animal析构函数" << endl;
//}
class Cat : public Animal
{
public:
void speak()
{
cout << *m_Name << "小猫说话" << endl;
}
Cat(string name)
{
m_Name = new string(name);
}
~Cat()
{
cout << "Cat析构函数" << endl;
if (m_Name != NULL)
{
delete m_Name;
m_Name = NULL;
}
}
string* m_Name;
};
void testA() {
Animal* animal = new Cat("Tom");
animal->speak();
delete animal;
}
int main()
{
testA();
system("pause");
return 0;
}
总结:
- 虚析构或纯虚析构就是用来解决通过父类指针释放子类对象
- 如果子类中没有堆区数据,可以不写虚析构或纯虚析构
- 拥有纯虚析构函数的类也属于抽象类
多态案例三:电脑组装
案例描述:
电脑主要组成部件为CPU(用于计算),显卡(用于显示),内存条(用于临时存储)
将每个零件封装出抽象基类,并且提供不同的厂商生成不同的零件,例如Intel厂商和Lenovo厂商
创建电脑类提供让电脑工作的函数,并且调用每个零件工作的接口
测试是组装三台不同的电脑进行工作
示例:
#include <iostream>
using namespace std;
// CPU抽象类
class CPU
{
public:
virtual void calculate() = 0;
};
// 显卡抽象类
class VideoCard
{
public:
virtual void display() = 0;
};
// 内存条抽象类
class Memory
{
public:
virtual void storage() = 0;
};
// 电脑类
class Computer
{
public:
Computer(CPU* cpu, VideoCard* vc, Memory* mem)
{
m_cpu = cpu;
m_vc = vc;
m_mem = mem;
}
// 工作的函数
void work()
{
m_cpu->calculate();
m_vc->display();
m_mem->storage();
}
~Computer()
{
if (m_cpu != NULL)
{
delete m_cpu;
m_cpu = NULL;
}
if (m_vc != NULL)
{
delete m_vc;
m_vc = NULL;
}
if (m_mem != NULL)
{
delete m_mem;
m_mem = NULL;
}
}
private:
CPU* m_cpu;
VideoCard* m_vc;
Memory* m_mem;
};
// 具体的产商
//Intel
class IntelCPU : public CPU
{
public:
virtual void calculate() override
{
cout << "Intel的CPU开始工作了!" << endl;
}
};
class IntelVideoCard : public VideoCard
{
public:
// 通过 VideoCard 继承
virtual void display() override
{
cout << "Intel的显卡开始工作了!" << endl;
}
};
class IntelMemory : public Memory
{
// 通过 Memory 继承
virtual void storage() override
{
cout << "Intel的内存条开始工作了!" << endl;
}
};
// AMD产商
class AMDCPU : public CPU
{
public:
virtual void calculate() override
{
cout << "AMD的CPU开始工作了!" << endl;
}
};
class AMDVideoCard : public VideoCard
{
public:
// 通过 VideoCard 继承
virtual void display() override
{
cout << "AMD的显卡开始工作了!" << endl;
}
};
class AMDMemory : public Memory
{
// 通过 Memory 继承
virtual void storage() override
{
cout << "AMD的内存条开始工作了!" << endl;
}
};
void testA()
{
// 第一台电脑的零件
CPU* intelCpu = new IntelCPU;
VideoCard* intelCard = new IntelVideoCard;
Memory* intelMem = new IntelMemory;
// 创建第一台电脑
Computer* computer = new Computer(intelCpu, intelCard, intelMem);
computer->work();
delete computer;
// 第二台电脑的零件
CPU* intelCpu_1 = new AMDCPU;
VideoCard* intelCard_1 = new AMDVideoCard;
Memory* intelMem_1 = new AMDMemory;
// 创建第一台电脑
Computer* computer_1 = new Computer(intelCpu_1, intelCard_1, intelMem_1);
computer_1->work();
delete computer_1;
}
int main()
{
testA();
system("pause");
return 0;
}