【C++】类和对象
C++面向对象的三大特性:封装、继承、多态。
C++认为万事万物都皆为对象,对象上有其属性和行为。
一、封装
1.1 封装的意义:
- 将属性和行为作为一个整体,表现生活中的事物;
- 将属性和行为加以权限控制。
语法:class 类名{ 访问权限:属性 / 行为};
【封装意义 1 的代码示例】
#include <iostream>
using namespace std;
const double PI = 3.14;
class Circle
{
public:
//属性
int r;
//行为
double getZC()
{
return 2 * PI * r;
}
};
int main(){
//实例化
Circle c1;
c1.r = 10;
cout<<"The ZC is "<<c1.getZC()<<endl;
return 0;
}
访问的权限有三种:
public(公共权限):类内可以访问,类外不能访问;
protected(保护权限):类内可以访问,类外不能访问,继承的子类可以访问父类保护权限的成员和方法;
private(私有权限,默认权限):类内可以访问,类外不能访问,继承的子类不能访问父类保护权限的成员和方法。
【封装意义2 的代码示例】
#include <iostream>
using namespace std;
class Person
{
private:
int myPassword;
protected:
string myCar;
public:
string myName;
void func()
{
myName = "zhangsan";
myCar = "tuolaji";
myPassword = 123;
}
};
int main(){
//实例化
Person p1;
p1.myName = "lisi";
p1.func();
return 0;
}
1.2 结构体(struct)和类(class)的区别
struct的默认权限是公共的 public; class的默认权限是私有的private。
二、对象的初始化和清理
2.1 构造函数和析构函数
构造函数:主要作用在于创建空对象时为对象的成员属性赋值,构造函数由编译器自动调用,无须手动调用;
析构函数:主要作用在于对象销毁前系统自动调用,执行一些清理工作。
构造函数语法:
类名(){}
- 构造函数,没有返回值也不写void;(与析构函数相同)
- 函数名称与类名相同;
- 构造函数可以有参数,因此可以发生重载;
- 程序在调用对象时会自动调用构造函数,无需手动调用,而且只会调用一次。(与析构函数相同)
析构函数语法
~类名(){}
- 析构函数,没有返回值,也不写void;(与构造函数相同)
- 函数名称与类名相同,在名称前加上符号~;
- 析构函数不可以有参数,因此不可以发生重载;
- 程序在对象销毁前会自动调用析构函数,无需手动调用,而且只会调用一次。(与构造函数相同)
【代码示例】
#include <iostream>
using namespace std;
class Person
{
public:
Person()
{
age = 18;
cout<<"Person()"<<endl;
}
~Person()
{
age=0;
cout<<"~Person()"<<endl;
}
int getAge()
{
return age;
}
private:
int age;
string name;
};
int test01(Person p)
{
cout<<"test01: &p= "<<(long)&p<<endl;
int age=p.getAge();
return age;
}
int main()
{
// 实例化
Person p;
cout<<"main: &p= "<<(long)&p<<endl;
int age = test01(p);
cout<<"age="<<age<<endl;
return 0;
}
2.2 构造函数的分类及调用
【两种分类方式】
按参数分为:有参构造和无参构造(默认构造函数);
按类型分为:普通构造和拷贝构造
【三种调用方式】
括号法
显示法
隐式转换法
【代码示例】
#include <iostream>
using namespace std;
class Person
{
public:
Person()
{
cout << "wucan Person()" << endl;
}
Person(int a)
{
age = a;
cout << "youcan Person()" << endl;
}
// copy constructor
Person(const Person &p)
{
age = p.age;
cout << "copy constructor" << endl;
}
~Person()
{
cout << "age=" << age << endl;
cout << "~Person()" << endl;
}
void setAge(int a)
{
age = a;
}
int getAge()
{
return age;
}
private:
int age;
string name;
};
void test01()
{
// 1.括号法
Person p1;
Person p2(10);
Person p3(p2);
// 2.显示法
Person p4;
Person p5 = Person(20);
Person p6 = Person(p5);
// 3.隐式转换法
Person p7 = 30;
Person p8 = p7;
}
int main()
{
// 实例化
test01();
return 0;
}
【注意】
- 使用括号法时,调用默认构造函数不要加(),
Person p1(); 编译器会认为这是一个函数的声明,不是在创建对象。- 使用显示法时,在显示法的 "=“右侧的"Person(20)”,若只写Person(20); ,这种称为匿名对象,特点是当前行执行结束后,系统会立即回收匿名对象。
- 不要利用拷贝函数构造函数来初始化匿名对象。例如:Person(p3);编译器认为Person(p3)等价于Person p3(对象声明)
- 一个函数内存在多个对象时,按照“后进先出”的规则执行析构函数。
2.3 拷贝构造函数的调用时机
C++中拷贝构造函数调用时机有三种情况:
- 使用一个已经创建完毕的对象来初始化一个新对象;
- 以值传递的方式给函数参数传值;
- 以值传递方式返回局部对象。
【代码示例】
#include <iostream>
using namespace std;
class Person
{
public:
Person()
{
mAge = 18;
cout << "wucan Person()" << endl;
}
Person(int age)
{
mAge = age;
cout << "youcan Person()" << endl;
}
// copy constructor
Person(const Person &p)
{
mAge = p.mAge;
cout << "copy constructor" << endl;
}
~Person()
{
cout << "age=" << mAge << endl;
cout << "~Person()" << endl;
}
void setAge(int age)
{
mAge = age;
}
int getAge()
{
return mAge;
}
private:
int mAge;
};
// 1. 使用一个已经创建完毕的对象来初始化一个新对象;
void test01()
{
Person p1(20);
Person p2(p1);
}
// 2. 值传递的方式给函数参数传值;
void doWork(Person p)
{
cout << "doWork address: " << &p << endl;
}
void test02()
{
Person p;
cout << "test02 address: " << &p << endl;
doWork(p);
}
// 3. 以值传递方式返回局部对象。
Person doWork2()
{
Person p;
cout << "doWork2 address: " << &p << endl;
return p;
}
void test03()
{
Person p = doWork2();
p.setAge(24);
cout << "test03 address: " << &p << endl;
}
int main()
{
// 实例化
Person p1(20);
Person p2(p1);
cout << "address: " << &p1 << endl;
cout << "address: " << &p2 << endl;
test02();
test03();
return 0;
}
【打印结果】
youcan Person()
copy constructor
address: 0x7fffffffdcc0
address: 0x7fffffffdcc4
wucan Person()
test02 address: 0x7fffffffdc90
copy constructor
doWork address: 0x7fffffffdc94
age=18
~Person()
age=18
~Person()
wucan Person()
doWork2 address: 0x7fffffffdc94
test03 address: 0x7fffffffdc94
age=24
~Person()
age=20
~Person()
age=20
~Person()
【拷贝函数的地址解释】
- 使用拷贝函数直接声明的对象,以及使用值传递的方式给函数传值时,是将原对象的成员变量赋值给新的对象成员变量(新的地址);
- 对于以值传递返回局部对象,会发生命名返回值优化(NRVO),所以两个对象的地址是一样的,详见C++中的返回值优化(RVO)
2.4 构造函数的调用规则
默认情况下,C++编译器至少给一个类添加3个函数
- 默认构造函数(无参,函数体为空);
- 默认析构函数(无参,函数体为空);
- 默认拷贝构造函数,对属性值进行值拷贝。
构造函数调用规则:
- 如果用户定义有参构造函数,C++不再提供默认无参构造函数,但是会提供默认拷贝构造;
- 如果用户定义拷贝构造函数,C++不再提供其他构造函数,但需手动实现无参或有参构造函数。
2.5 深拷贝和浅拷贝
- 浅拷贝:简单的赋值拷贝操作(“=”),浅拷贝会造成堆区的内存重复释放,需使用深拷贝解决。
- 深拷贝:在堆区重新申请空间进行拷贝操作。
【代码示例】
#include <iostream>
using namespace std;
class Person
{
public:
Person()
{
cout<<"default structor"<<endl;
}
Person(int age, int height)
{
mAge = age;
mHeight = new int(height);
cout<<"youcan structor"<<endl;
}
Person (const Person &p)
{
mAge = p.mAge;
//mHeight = p.mHeight; 编译器默认的拷贝操作
mHeight = new int(*p.mHeight);
cout<<"deep copy"<<endl;
}
~Person()
{
if (mHeight != NULL)
{
delete mHeight;
mHeight = NULL;
}
cout<<"destructor"<<endl;
}
int mAge;
int *mHeight;
};
int main()
{
// 实例化
Person p1(18, 180);
cout<<"p1 age: "<<p1.mAge<<" height:"<<*p1.mHeight<<endl;
Person p2(p1);
cout<<"p2 age: "<<p2.mAge<<" height:"<<*p2.mHeight<<endl;
return 0;
}
2.6 初始化列表
作用:C++提供了初始化列表语法,用来初始化属性。
语法:构造函数(): 属性1(值1), 属性2(值2), …{ }
【代码示例】
#include <iostream>
using namespace std;
class Person
{
public:
int mA, mB, mC;
// Person(int a, int b, int c)
// {
// mA = a;
// mB = b;
// mC = c;
// }
Person(int a, int b, int c): mA(a), mB(b), mC(c)
{
}
};
int main()
{
// 实例化
Person p1(10, 20, 30);
cout<<"p1 mA: "<<p1.mA<<" mB:"<<p1.mB<<" mC: "<<p1.mC<<endl;
return 0;
}
2.7 类对象作为类成员
C++类中的成员可以是另一个类的对象,我们称该成员为对象成员。
【代码示例】
#include <iostream>
using namespace std;
class Phone
{
public:
string m_PName;
Phone(string PName): m_PName(PName)
{
cout<<"phone first"<<endl;
}
~Phone()
{
cout<<"phone destructor first"<<endl;
}
};
class Person
{
public:
string mName;
Phone mPhone;
Person(string name, string phone):mName(name), mPhone(phone) //mPhone(phone) is same as Phone mPhone = phone.隐式转换法
{
cout<<"Person second"<<endl;
}
~Person()
{
cout<<"Person destructor second"<<endl;
}
};
int main()
{
// 实例化
Person p1("zhangsan", "xiaomi13");
cout<<"p1 name: "<<p1.mName<<" phone: "<<p1.mPhone.m_PName<<endl;
return 0;
}
当其他类对象作为本类成员,构造的时候先构造对象成员,再构成自身,析构相反。
2.8 静态成员
静态成员就是在成员变量和成员函数前加上关键字static,成为静态成员。
静态成员分为:
- 静态成员变量
所有对象共享同一份数据;
在编译阶段分配内存(全局区);
类内声明,必须类外初始化。
【注意】静态成员变量不属于某一个对象,所有对象都共享同一份数据,因此静态成员变量有两种访问方式:通过对象进行访问和通过类名进行访问。
- 静态成员函数
所有对象共享同一个函数;
静态成员函数只能访问静态成员变量。
【代码示例】
#include <iostream>
using namespace std;
class Person
{
public:
static int mA;
static void func()
{
cout << "static function" << endl;
}
private:
static int mB; // 静态成员变量也是有访问权限的, 类外访问不到
};
// 通过类名进行访问
int Person::mA = 100;
int main()
{
// 实例化
Person p;
// 通过对象进行访问
p.func();
// 通过类名进行访问
Person::func();
return 0;
}
三、C++对象模型和this指针
3.1 成员变量和成员函数分开存储
在C++中,类内的成员变量和成员函数分开存储,只有非静态成员变量才属于类的对象上。
【代码示例】
#include <iostream>
using namespace std;
class Person
{
public:
int mA;
static int mB;
void func() // func does not belongs to class Person.
{
}
static void func2() // func2 does not belongs to class Person.
{
}
};
int Person::mB = 10; // mB does not belongs to class Person.
int main()
{
// 实例化
Person p;
cout << "Length of p is " << sizeof(p) << endl;//打印结果是4
return 0;
}
【注意】
空对象占用空间为1,因为C++编译器会给每个空对象也分配一个字节空间,是为了区分空对象占内存的位置,每一个空对象也应该有一个独一无二的地址。
3.2 this指针的概念
每一个非静态成员函数只会诞生一份函数实例,也就是说多个同类型的对象会公用一块代码,那这一块代码是如何区分哪个对象调用自己的呢?
C++通过提供特殊的对象指针,this指针,解决上述问题。this指针指向被调用的成员函数所属的对象。
this指针是隐含在每一个非静态成员函数内的一种指针,this指针不需要定义,直接使用即可。
【用途】
- 当形参和成员变量同名时,可用this指针来区分;
- 在类的非静态成员函数中返回对象本身,可使用return *this。
【代码示例】
#include <iostream>
using namespace std;
class Person
{
public:
int age;
Person(int age)
{
//this指针指向被调用的成员函数所属的对象
this->age=age;
}
// 在类的非静态成员函数中返回对象本身,可使用return *this
Person& PersonAddAge(Person &p)
{
this->age += p.age;
return *this;
}
};
int main()
{
// 实例化
Person p(18), p1(2);
p.PersonAddAge(p1).PersonAddAge(p1).PersonAddAge(p1);
cout << "age is " << p.age << endl;//打印结果是24
return 0;
}
当返回值类型为class时,即上述代码14行改为“Person PersonAddAge(Person &p)”,这时会调用拷贝函数(拷贝函数调用时机三 以值传递方式返回局部对象),则打印结果为20。
3.3 空指针访问成员函数
C++中空指针也可以调用成员函数,但需注意有没有用到this指针。如果用到this指针,需要加以判断保证代码的健壮性。
【代码示例】
#include <iostream>
using namespace std;
class Person
{
public:
int age;
void showClassName()
{
cout << "This is Class Person." << endl;
}
void showPersonAge()
{
if (this != NULL)
{
cout << "age = " << this->age << endl; // the error is that this is NULL.
}
}
};
int main()
{
// 实例化
Person *p = NULL;
p->showClassName();
p->showPersonAge();
return 0;
}
3.4 const修饰成员函数
【常函数】
1.成员函数后加const,称这个函数为常函数;
2.常函数内不可以修改成员属性;
3.成员属性声明时加关键字mutable后,在常函数中依然可以修改。
【常对象】
- 声明对象前加const称该对象为常对象;
- 常对象只能调用常函数。
【代码示例】
#include <iostream>
using namespace std;
class Person
{
public:
// this指针的本质是指针常量(* const),this指针的指向是不可以修改的
// 在成员函数后面加const,修饰的是this指针的指向,让指针指向的值也不可以修改
void showPerson() const
{
this->mB = 100;
}
void func()
{
}
Person()
{
}
int mA;
mutable int mB;
};
int main()
{
// 实例化
const Person p; //
// p.mA=100; error
p.mB = 100; // can be changed
p.showPerson();
// p.func(); error
return 0;
}
【注意】使用vscode编程时,在代码25行const Person p; 如果class Person没有构造函数,则会报错,需手动添加无参或者有参构造函数。
四、友元
在程序里,有些私有属性也想让类外的一些特殊函数或者类进行访问,就需要用到友元的技术。友元的目的就是让一个函数或者类访问另一个类中私有成员。友元的关键字为friend。
友元的三种实现:
- 全局函数做友元
- 类做友元
- 成员函数做友元
4.1 全局函数做友元
语法:在类中写上“ friend 返回值 函数名称(class &类名); ”
【示例代码】
#include <iostream>
using namespace std;
class Building
{
friend void goodGay(Building &building);
public:
string mSittingRoom;
Building()
{
mSittingRoom = "sittingRoom";
mBedRoom = "bedRoom";
}
private:
string mBedRoom;
};
void goodGay(Building &building)
{
cout << "global is visiting " << building.mSittingRoom << endl;
cout << "global is visiting " << building.mBedRoom << endl;
}
int main()
{
// 实例化
Building b;
goodGay(b);
return 0;
}
4.2 类做友元
语法:在类中写上“ friend class 类名; ”
【示例代码】
#include <iostream>
using namespace std;
class Building
{
friend class GoodGay;
public:
string mSittingRoom;
Building();
private:
string mBedRoom;
};
class GoodGay
{
public:
GoodGay();
void visit();
Building *building;
};
Building::Building()
{
mSittingRoom = "sittingRoom";
mBedRoom = "bedRoom";
}
GoodGay::GoodGay()
{
building = new Building;
}
void GoodGay::visit()
{
cout << "GoodGay is visiting " << building->mSittingRoom << endl;
cout << "GoodGay is visiting " << building->mBedRoom << endl;
}
int main()
{
// 实例化
Building b;
GoodGay g;
g.visit();
return 0;
}
4.3成员函数做友元
语法:在类中写上“ friend 返回值 类名::函数名称(参数); ”
【示例代码】
#include <iostream>
using namespace std;
class Building;//类在使用前先声明
class GoodGay
{
public:
GoodGay();
void visit();
void visit2();
Building *building;
};
class Building
{
// friend class GoodGay;
friend void GoodGay::visit();
public:
string mSittingRoom;
Building();
private:
string mBedRoom;
};
Building::Building()
{
mSittingRoom = "sittingRoom";
mBedRoom = "bedRoom";
}
GoodGay::GoodGay()
{
building = new Building;
}
void GoodGay::visit()
{
cout << "GoodGay visit is visiting " << building->mSittingRoom << endl;
cout << "GoodGay visit is visiting " << building->mBedRoom << endl;
}
void GoodGay::visit2()
{
cout << "GoodGay visit2 is visiting " << building->mSittingRoom << endl;
// cout << "GoodGay visit2 is visiting " << building->mBedRoom << endl;
}
int main()
{
// 实例化
Building b;
GoodGay g;
g.visit();
g.visit2();
return 0;
}
五、运算符重载
概念:对已有的运算符重新进行定义,赋予其另一种功能,已适应不同的数据类型。
5.1 加号运算符重载
【代码示例】
#include <iostream>
using namespace std;
class Person
{
public:
int mA;
int mB;
// Person operator+(Person &p)
// {
// Person temp;
// temp.mA = this->mA + p.mA;
// temp.mB = this->mB + p.mB;
// return temp;
// }
};
Person operator+(Person &p1, Person &p2)
{
Person temp;
temp.mA = p1.mA + p2.mA;
temp.mB = p1.mB + p2.mB;
return temp;
}
// 运算符函数重载
Person operator+(Person &p1, int a)
{
Person temp;
temp.mA = p1.mA + a;
temp.mB = p1.mB + a;
return temp;
}
int main()
{
// 实例化
Person p1, p2, p3, p4;
p1.mA = 10;
p1.mB = 10;
p2.mA = 20;
p2.mB = 20;
p3 = p1 + p2;
// 成员函数重载本质调用 p3 = p1.operator+(p2);
// 全局函数重载本质调用 p3 = operator+(p1,p2);
cout << "p3 mA=" << p3.mA << " mB=" << p3.mB << endl;//打印30
p4 = p1 + 30;
cout << "p4 mA=" << p4.mA << " mB=" << p4.mB << endl;//打印40
return 0;
}
5.1 左移运算符重载
作用:可以输出自定义数据类型。
【代码示例】
#include <iostream>
using namespace std;
class Person
{
// friend ostream &operator<<(ostream &cout, Person &p);
private:
int mA;
int mB;
public:
Person(int a, int b)
{
mA = a;
mB = b;
}
// p.operator<<(cout),简化版本p<<cout
// 不利用成员函数重载<<运算符,因为无法实现cout在左侧
ostream &operator<<(ostream &cout)
{
cout << "mA=" << mA << " mB=" << mB;
return cout;
}
};
// ostream& operator<<(ostream &cout, Person &p)//本质 operator<<(cout, p) 简化 cout<<p;
// //这里的cout可以修改名字,引用相当于起别名
// {
// cout<<"mA="<<p.mA<<" mB="<<p.mB;
// return cout;
// }
int main()
{
// 实例化
Person p1(10, 10);
// cout << p1 << endl; //利用成员函数重载<<运算符,cout在左侧
p1 << cout << endl; // 利用成员函数重载<<运算符,Person 在左侧
return 0;
}
5.3 递增运算符重载
作用:通过重载递增运算符,实现自己的整形数据。
【代码示例】
#include <iostream>
using namespace std;
class MyInteger
{
friend ostream &operator<<(ostream &cout, MyInteger &myinteger);
public:
MyInteger()
{
mNum = 0;
}
// 重载前置++运算符
MyInteger &operator++()
{
++mNum;
return *this;
}
// 重置后置++运算符 int代表占位参数,可以用于区分前置和后置递增,且必须为int
MyInteger &operator++(int)
{
// 先 记录当时的结果
MyInteger *temp = new MyInteger(*this);//这里申请了堆空间,但不会释放了
//如果按照下行的写,则需要将左移运算符重载函数的第二个形参的&去掉
//MyInteger temp = *this;
// 后 递增
mNum++;
// 最后将记录结果返回
return *temp;
}
private:
int mNum;
};
ostream &operator<<(ostream &cout, MyInteger &myinteger)
{
cout << myinteger.mNum;
return cout;
}
int main()
{
// 实例化
MyInteger myinteger;
// cout << ++myinteger << endl;//++(++myinteger) is OK
cout << myinteger++ << endl; //(myinteger++)++ is not OK
cout << myinteger << endl;
return 0;
}
【注意】
- 重载函数返回对象而不是对象的引用时,vscode会报错no match for ‘operator<<’ (operand types are ‘std::ostream’ {aka ‘std::basic_ostream’} and ‘MyInteger’)。返回引用是一直对一个数据进行递增。
- C++中,前置递增调用无参的重载函数,后置递增调用有参的重载函数
5.4 赋值运算符重载
C++编译器至少给一个类添加4个函数:
- 默认构造函数(无参,函数体为空)
- 默认析构函数(无参,函数体为空)
- 默认拷贝构造函数,对属性值进行值拷贝
- 赋值运算符operator=,对属性值进行拷贝
如果类中有属性指向堆区,做赋值操作时也会出现深浅拷贝的问题。
【代码示例】
#include <iostream>
using namespace std;
class Person
{
public:
Person(int age)
{
mAge = new int(age);
}
// Person(const Person &p)
// {
// mAge = new int(*p.mAge);
// }
~Person()
{
if (mAge != NULL)
{
delete mAge;
mAge = NULL;
}
}
Person &operator=(Person &p)
{
// 应该先判断是否有属性在堆区,如果有先释放干净,再深拷贝
if (mAge != NULL)
{
delete mAge;
mAge = NULL;
}
mAge = new int(*p.mAge);
return *this;
}
int *mAge;
};
int main()
{
// 实例化
Person p1(18);
Person p2(20);
Person p3(30);
p3 = p2 = p1;
cout << "age1=" << *p1.mAge << endl;//打印18
cout << "age2=" << *p2.mAge << endl;//打印18
cout << "age3=" << *p3.mAge << endl;//打印18
return 0;
}
5.5 关系运算符
作用:重载关系运算符,可以让两个自定义类型对象进行对比操作。
【代码示例】
#include <iostream>
using namespace std;
class Person
{
public:
Person(string name, int age)
{
mName = name;
mAge = age;
}
bool operator==(const Person &p)
{
if (mName==p.mName && mAge == p.mAge)
{
return true;
}
return false;
}
int mAge;
string mName;
};
int main()
{
// 实例化
Person p1("tom", 18);
Person p2("tom", 19);
cout<<(p1==p2)<<endl;
return 0;
}
5.6 函数调用运算符重载
函数调用运算符()也可以重载,由于重载后使用的方式非常像函数的使用,因此称为仿函数,仿函数没有固定写法,非常灵活。
【代码示例】
#include <iostream>
using namespace std;
class MyPrint
{
public:
void operator()(string test)
{
cout << test << endl;
}
void func(string test)
{
cout << test << endl;
}
};
int main()
{
// 实例化
MyPrint print;
print("hello");
MyPrint()("world"); //匿名函数对象
return 0;
}
六、继承
继承是面向对象的三大特性之一,有些类与类之间存在特殊的关系,我们可以利用继承的技术,减少重复代码。
6.1 继承的基本语法
语法:class 子类 : 继承方式 父类
子类也称为派生类,父类也称为基类。
【代码示例】
#include <iostream>
using namespace std;
class BasePage
{
public:
void head()
{
cout << "head" << endl;
}
void footer()
{
cout << "footer" << endl;
}
};
class JAVA : public BasePage
{
public:
void content()
{
cout << "JAVA" << endl;
}
};
class PYTHON : public BasePage
{
public:
void content()
{
cout << "PYTHON" << endl;
}
};
class CPP : public BasePage
{
public:
void content()
{
cout << "CPP" << endl;
}
};
int main()
{
// 实例化
JAVA().head();
JAVA().footer();
JAVA().content();
return 0;
}
6.2 继承方式
继承方式一共有三种:公共继承、保护继承和私有继承。
【代码示例】
#include <iostream>
using namespace std;
class Base1
{
public:
int mA;
protected:
int mB;
private:
int mC;
};
class Son1 : public Base1
{
public:
Son1()
{
mA = 10; // 父类中的公共权限成员到子类中依然是公共权限
mB = 10; // 父类中的保护权限成员到子类中依然是保护权限
// mC = 10;父类中的私有权限成员子类访问不到
}
};
class Son2 : protected Base1
{
public:
Son2()
{
mA = 10; // 父类中的公共权限成员到子类中 是保护权限
mB = 10; // 父类中的保护权限成员到子类中依然是保护权限
// mC = 10;父类中的私有权限成员子类访问不到
}
};
class Son3 : private Base1
{
public:
Son3()
{
mA = 10; // 父类中的公共权限成员到子类中 是私有权限
mB = 10; // 父类中的保护权限成员到子类中 是私有权限
// mC = 10;父类中的私有权限成员子类访问不到
}
};
class GrandSon3 : private Son3
{
public:
GrandSon3()
{
// mA = 10; // Son3中的私有权限成员到GrandSon3子类中 是私有权限
// mB = 10; // Son3中的私有权限成员到GrandSon3子类中 是私有权限
// mC = 10;Son3中的私有权限成员子类访问不到
}
};
int main()
{
// 实例化
Son1().mA;
// Son1().mB; son1中mB是保护权限 类外访问不到
// Son2().mA; son2中mA是保护权限 类外访问不到
// Son2().mB; son2中mB是保护权限 类外访问不到
// Son3().mA; son3中mA是私有权限 类外访问不到
// Son3().mB; son3中mB是私有权限 类外访问不到
return 0;
}
【如图所示】
6.3 继承中的对象模型
从父类继承过来的成员,哪些属于子类对象?
父类中所有非静态成员属性都会被子类继承下去,父类中的私有成员属性被编译器隐藏了,因此访问不到,但是确实被继承了。
【代码示例】
#include <iostream>
using namespace std;
class Base
{
public:
int mA;
protected:
int mB;
private:
int mC;
};
class Son : public Base
{
public:
Son()
{
mA = 10; // 父类中的公共权限成员到子类中依然是公共权限
mB = 10; // 父类中的保护权限成员到子类中依然是保护权限
// mC = 10;父类中的私有权限成员子类访问不到
}
int mD;
};
int main()
{
// 实例化
cout << "sizeof son: " << sizeof(Son) << endl;//打印16
return 0;
}
6.4 继承中的构造和析构顺序
子类继承父类后,当创建子类对象,也会调用父类的构造函数。
继承中的构造和析构顺序:先构造父类,再构造子类;析构的顺序与构造的顺序相反,先析构子类,再析构父类。
【代码示例】
#include <iostream>
using namespace std;
class Base
{
public:
int mA;
Base()
{
cout << "Base default structor" << endl;
}
~Base()
{
cout << "Base destructor" << endl;
}
};
class Son : public Base
{
public:
Son()
{
cout << "Son default structor" << endl;
}
~Son()
{
cout << "Son destructor" << endl;
}
};
int main()
{
// 实例化
Son s;
return 0;
}
6.5 继承同名成员处理方式
当子类与父类出现同名的成员时,访问子类同名成员直接访问即可,访问父类同名成员,需要加作用域。
【代码示例】
#include <iostream>
using namespace std;
class Base
{
public:
int mA;
Base()
{
mA = 10;
}
void show()
{
cout << "father's mA " << mA << endl;
}
void show(int a)
{
mA = a;
cout << "father's new mA " << mA << endl;
}
};
class Son : public Base
{
public:
int mA;
Son()
{
mA = 20;
}
void show()
{
cout << "son's mA " << mA << endl;
}
};
int main()
{
// 实例化
Son s;
// cout << s.mA << endl;//打印20
// cout << s.Base::mA << endl;//打印10
s.show();//打印son's mA 20
s.Base::show();//打印father's mA 10
s.Base::show(100);//father's new mA 100
return 0;
}
【注意】如果子类中出现和父类同名的成员函数,子类的同名成员会隐藏掉父类中所有同名成员函数。
6.6 继承中同名静态成员处理方式
与同名非静态成员处理方式一致,当子类与父类出现同名的成员时,访问子类同名成员直接访问即可,访问父类同名成员,需要加作用域。
【代码示例】
#include <iostream>
using namespace std;
class Base
{
public:
static int mA;
static void show()
{
cout << "father's mA " << mA << endl;
}
static void show(int a)
{
mA = a;
cout << "father's new mA " << mA << endl;
}
};
int Base::mA=10;
class Son : public Base
{
public:
static int mA;
static void show()
{
cout << "son's mA " << mA << endl;
}
};
int Son::mA=20;
int main()
{
// 通过对象访问
Son s;
cout << s.mA << endl;
cout << s.Base::mA << endl;
s.show();
s.Base::show();
s.Base::show(100);//如果子类中出现和父类同名的成员函数,子类的同名成员会隐藏掉父类中所有同名成员函数。
//通过类名访问,第一个::代表通过类名访问,第二个::代表访问父类作用域下
cout << Son::mA << endl;
cout << Son::Base::mA << endl;
Son::show();
Son::Base::show();
return 0;
}
【注意】静态成员在类内声明,类外初始化。
6.7 多继承语法
C++允许一个类继承多个类。
语法:class 子类:继承方式 父类1,继承方式 父类2…
多继承可能会引发父类中有同名成员出现,需要加作用域区分。
C++实际开发中不建议使用多继承。
【代码示例】
#include <iostream>
using namespace std;
class Base1
{
public:
int mA;
Base1()
{
mA = 10;
}
};
class Base2
{
public:
int mA;
Base2()
{
mA = 20;
}
};
class Son : public Base1, public Base2
{
public:
int mC;
Son()
{
mC = 30;
}
};
int main()
{
// 通过对象访问
Son s;
cout << "sizeof of son " << sizeof(s) << endl; // 12
cout << "mA=" << s.Base2::mA << endl;
return 0;
}
6.8 菱形继承(虚继承 virtual)
菱形继承概念:
两个派生类继承同一个类,又有某个类同时继承这两个派生类。这种继承被称为菱形继承或者钻石继承。
【示例代码】
#include <iostream>
using namespace std;
class Animal
{
public:
int mAge;
};
// 继承之前,加上关键字virtual,变为虚继承
// Animal类称为虚基类
class Sheep : virtual public Animal
{
};
class Tuo : virtual public Animal
{
};
class SheepTuo : public Sheep, public Tuo
{
};
int main()
{
// 通过对象访问
SheepTuo st;
st.Sheep::mAge = 18;
st.Tuo::mAge = 28;
cout << "sizeof of SheepTuo " << sizeof(SheepTuo) << endl; // print 24
cout << "st.Sheep::mAge=" << st.Sheep::mAge << endl;// print 28
cout << "st.Tuo::mAge" << st.Tuo::mAge << endl;// print 28
cout << "st.mAge" << st.mAge << endl;// print 28
// 菱形继承导致数据有两份,资源浪费
return 0;
}
【注意】
- vbptr,虚基类指针,v是virtual,b是base,ptr是pointer。vbptr指向vbtable(virtual base table,虚基类表)。
2. sizeof(SheepTuo)结果是24,分析:两个指针占16字节,一个int变量占4字节
七、多态
7.1 多态的基本概念
多态分为两类:
- 静态多态:函数重载和运算符重载属于静态多态,复用函数名;
- 动态多态:派生类和虚函数实现运行时多态
静态多态和动态多态的区别:
- 静态多态的函数地址早绑定——编译阶段确定函数地址
- 动态多态的函数地址晚绑定——运行阶段确定函数地址
动态满足条件
- 有继承关系;
- 子类重写父类的虚函数
动态多态使用:父类的指针或者引用指向子类的对象。
【代码示例】
#include <iostream>
using namespace std;
class Animal
{
public:
//虚函数
virtual void speak()
{
cout << "动物在说话" << endl;
}
};
class Cat : public Animal
{
public:
void speak()
{
cout << "小猫喵喵叫" << endl;
}
};
class Dog :public Animal
{
public:
void speak()
{
cout << "小狗汪汪叫" << endl;
}
};
//地址早绑定,在编译阶段确定函数地址
//如果执行让猫说话,那么这个函数地址就不能提前绑定,需在运行阶段进行绑定,即地址晚绑定,使用virtual
void doSpeak(Animal &animal)
{
animal.speak();
}
int main()
{
Cat cat;
doSpeak(cat);
Dog dog;
doSpeak(dog);
return 0;
}
【多态案例——计算器类】
描述:分别利用普通写法和多态技术,设计实现两个操作数进行运算的计算器类
多态的优点:
- 代码组织结构清晰
- 可读性强
- 利于前期和后期的扩展以及维护
【实现代码】
#include <iostream>
using namespace std;
//普通方法
class Calculator
{
public:
int getResult(const char oper)
{
switch (oper)
{
case '+':
return num1 + num2;
case '-':
return num1 - num2;
case '*':
return num1 * num2;
case '/':
return num1 / num2;
}
//如果想扩展新的功能,需要修改源码
//在实际的开发原则中,提倡开闭原则(对扩展进行开发,对修改进行关闭)
}
int num1;
int num2;
};
//利用多态实现
//实现计算器的抽象类
class AbstractCalculator
{
public:
virtual int getResult()
{
return 0;
}
int num1;
int num2;
};
class AddCalculator: public AbstractCalculator
{
public:
int getResult()
{
return num1 + num2;
}
};
class SubCalculator : public AbstractCalculator
{
public:
int getResult()
{
return num1 - num2;
}
};
class MulCalculator : public AbstractCalculator
{
public:
int getResult()
{
return num1 * num2;
}
};
int main()
{
/* Calculator c;
c.num1 = 10;
c.num2 = 10;
cout<<c.num1<<" + " <<c.num2<<" = " << c.getResult('+') << endl;
cout << c.num1 << " - " << c.num2 << " = " << c.getResult('-') << endl;
cout << c.num1 << " * " << c.num2 << " = " << c.getResult('*') << endl;
cout << c.num1 << " / " << c.num2 << " = " << c.getResult('/') << endl;*/
//多态使用的条件:父类指针或者引用指向子类对象
AbstractCalculator* abc = new AddCalculator;
abc->num1 = 100;
abc->num2 = 10;
cout << abc->num1 << " + " << abc->num2 << " = " << abc->getResult() << endl;
delete abc;
abc = new SubCalculator;
abc->num1 = 100;
abc->num2 = 10;
cout << abc->num1 << " - " << abc->num2 << " = " << abc->getResult() << endl;
delete abc;
abc = new MulCalculator;
abc->num1 = 10;
abc->num2 = 10;
cout << abc->num1 << " * " << abc->num2 << " = " << abc->getResult() << endl;
delete abc;
return 0;
}
7.2 纯虚函数和抽象类
在多态中,通常父类中虚函数的实现是毫无意义的主要是调用子类重写的内容。因此可以将虚函数改为纯虚函数。
纯虚函数语法:virtual 返回值类型 函数名 (参数列表)= 0;
当类中有了纯虚函数,这个类也成为抽象类。
抽象类特点:
- 无法实例化对象
- 子类必须重写抽象类中的纯虚函数,否则也属于抽象类
【代码示例】
#include <iostream>
using namespace std;
class Base
{
public:
virtual void func() = 0;
};
class A :public Base
{
public:
void func()
{
cout << "子类A重写父类的纯虚函数" << endl;
}
};
int main()
{
//Base b; 抽象类无法实例化对象
Base *b = new A;
b->func();
return 0;
}
【多态案例2——制作饮品】
【实现代码】
#include <iostream>
using namespace std;
class AbstractDrinking
{
public:
virtual void ChongPao() = 0;
virtual void JiaLiao() = 0;
void ZhuShui()
{
cout << "开始煮水" << endl;
}
void DaoShui()
{
cout << "倒入杯中" << endl;
}
void makeDrink()
{
ZhuShui();
ChongPao();
DaoShui();
JiaLiao();
}
};
class Coffee : public AbstractDrinking
{
public:
void ChongPao()
{
cout << "冲泡咖啡" << endl;
}
void JiaLiao()
{
cout << "加糖和牛奶" << endl;
}
};
class Tea : public AbstractDrinking
{
public:
void ChongPao()
{
cout << "冲泡茶叶" << endl;
}
void JiaLiao()
{
cout << "加柠檬" << endl;
}
};
void doWork(AbstractDrinking* abd)
{
abd->makeDrink();
delete abd;
}
int main()
{
doWork(new Coffee);
doWork(new Tea);
return 0;
}
7.3 虚析构和纯虚析构
多态使用时,如果子类中有属性开辟到堆区,那么父类指针在释放时无法调用到子类的析构代码。
解决方法:将父类中的析构函数改为虚析构或者纯虚析构。
虚析构和纯虚析构共性:
- 可以解决父类指针释放子类对象
- 都需要有具体的函数实现
虚析构和纯虚析构的区别:如果是纯虚析构,该类属于抽象类,无法实例化对象。
虚析构语法:virtual ~类名(){}
纯虚析构的语法:virtual ~类名()=0; 类名::~类名(){}
【代码示例】
#include <iostream>
using namespace std;
class Animal
{
public:
Animal()
{
cout << "Animal构造函数调用" << endl;
}
//利用虚析构可以解决父类指针释放子类对象时不干净的问题
/*virtual ~Animal()
{
cout << "Animal析构函数调用" << endl;
}*/
//纯虚析构,需要声明也需要实现
//有了纯虚析构之后,这个类也属于抽象类,无法实例化对象
virtual ~Animal() = 0;
virtual void speak() = 0;
};
Animal::~Animal()
{
cout << "Animal纯虚析构函数调用" << endl;
}
class Cat :public Animal
{
public:
Cat(string name)
{
mName = new string(name);
}
void speak()
{
cout << *mName << "小猫喵喵叫" << endl;
}
~Cat()
{
if (mName != NULL)
{
cout << "Cat's 析构函数调用" << endl;
delete mName;
mName = NULL;
}
}
string* mName;
};
int main()
{
Animal* a = new Cat("Tom");
a->speak();
//父类指针在析构的时候,不会调用子类中的析构函数,导致子类如果有堆区属性,出现内存泄漏
delete a;
return 0;
}
【多态案例三——电脑组装】
案例描述:
电脑主要组成部件为CPU(用于计算),显卡(用于显示),内存条(用于存储)
将每个零件封装出抽象基类,并且提供不同的厂商生产不同的零件,例如Intel厂商和Lenovo厂商创建电脑类提供让电脑工作的函数,并且调用每个零件工作的接口
测试时组装三台不同的电脑进行工作
【实现代码】
#include <iostream>
using namespace std;
class CPU
{
public:
virtual void calculate() = 0;
};
class ViedoCard
{
public:
virtual void display() = 0;
};
class Memory
{
public:
virtual void storage() = 0;
};
class IntelCPU :public CPU
{
public:
void calculate()
{
cout << "Intel CPU is calculating." << endl;
}
};
class IntelViedoCard :public ViedoCard
{
public:
void display()
{
cout << "Intel Viedo card is working." << endl;
}
};
class IntelMemory :public Memory
{
public:
void storage()
{
cout << "Intel Memory is storaging." << endl;
}
};
class LenovoCPU :public CPU
{
public:
void calculate()
{
cout << "Lenovo CPU is calculating." << endl;
}
};
class LenovoViedoCard :public ViedoCard
{
public:
void display()
{
cout << "Lenovo Viedo card is working." << endl;
}
};
class LenovoMemory :public Memory
{
public:
void storage()
{
cout << "Lenovo Memory is storaging." << endl;
}
};
class Computer
{
public:
Computer(CPU* cpu, ViedoCard* vc, Memory* memory)
{
mCpu = cpu;
mVc = vc;
mMemory = memory;
}
void Work()
{
mCpu->calculate();
mVc->display();
mMemory->storage();
}
~Computer()
{
if (mCpu != NULL)
{
delete mCpu;
mCpu = NULL;
}
if (mVc != NULL)
{
delete mVc;
mVc = NULL;
}
if (mMemory != NULL)
{
delete mMemory;
mMemory = NULL;
}
}
private:
CPU* mCpu;
ViedoCard* mVc;
Memory* mMemory;
};
int main()
{
CPU* intelCPU = new IntelCPU;
ViedoCard* intelViedoCard = new IntelViedoCard;
Memory* intelMemory = new IntelMemory;
Computer* c1 = new Computer(intelCPU, intelViedoCard, intelMemory);
c1->Work();
delete c1;
cout << endl;
Computer* c2 = new Computer(new LenovoCPU, new LenovoViedoCard, new LenovoMemory);
c2->Work();
delete c2;
cout << endl;
Computer* c3 = new Computer(new IntelCPU, new LenovoViedoCard, new LenovoMemory);
c3->Work();
delete c3;
return 0;
}