目录
4.2 对象的初始化清理
- 在生活中我们所购买的点子产品大多都有恢复出厂设置,在某一天我们不使用的时候清楚自己的数据来保证自己信息的安全。
- C++中的面向对象来源生活,每个对象也会有初识设置以及对象销毁前的清理数据的设置。、
4.2.1 构造函数和析构函数
对象的初始化和清理也是两个非常重要的安全问题。
一个对象或者变量没有初识状态,对其使用后的后果是未知的。
同样的使用完一个对象或者变量,没有及时进行清理,也会造成一定的安全问题。
C++利用了构造函数和析构函数解决上述问题,这两个函数将会被编译器自动斓用,完成对象初始化和清理工作。对象的初始化和清理工作是编译器强制要我们做的事情,因此如果我们不提供构造和析构,编译器会提供,但是编译器提供的构造函数和析构函数是空实现。
- 构造函数:主要作用在于创建对象时为对象的成员属性赋值,构造函数由编译器自动调用,无须手动调用。
- 析构函数:主要作用在于对象销毁前系统自动调用,执行一些清理工作。
构造函数语法:类名(){}
- 构造函数没有返回值也不写void
- 函数名称与类名相同
- 构造函数可以有参数,因此可以发生重载
- 程序在调用对象的时候会自动调用构造,无须手动调用,而且只会调用一次
析构函数语法
~类名(){}
- 析构函数没有返回值也不写void
- 函数名称与类名相同,在名称前加上~
- 析构函数不可以有参数,因此不可以发生重载
- 程序在对象销毁前会自动调用析构,无须手动调用,而且只会调用一次
#include<iostream>
using namespace std;
class Person
{
public:
Person()
{
cout << "构造函数的调用" << endl;
}
~Person()
{
cout << "析构函数的调用" << endl;
}
//构造和析构都是必须有的实现,如果我们自己不提供,编译器会提供一个空实现的构造和析构
};
void test01()
{
Person p;//在栈上的数据,test01执行完之后会释放这个对象,释放这个对象前就会自动调用析构函数
}
int main(void)
{
test01();
//Person p;在main函数中析构函数也会被调用在按完任意键之后
system("pause");
return 0;
}
4.2.2 构造函数的分类及调用
两种分类方式:
- 按参数分为:有参构造和无参构造
- 按类型分为:普通构造和拷贝构造
三种调用方式:
- 括号法
- 显示法
- 隐式转换法
#include<iostream>
using namespace std;
class Person
{
public:
//构造函数
//构造函数-无参构造-编译器提供的就是无参的
Person()
{
cout << "Person的无参构造函数调用" << endl;
}
//构造函数-有参构造
Person(int a)
{
//将传入的人身上的所有属性,拷贝到我身上。
age = a;
cout << "Person的有参构造函数调用" << endl;
}
~Person()
{
cout << "Person的析构函数调用" << endl;
}
//
//拷贝构造函数
Person(const Person &p)
{
age = p.age;
cout << "拷贝构造函数调用" << endl;
}
int age;
string name;
};
int main(void)
{
//Person p;//默认构造函数调用
///*注意:使用默认构造函数的时候,不要加(),编译器会认为这是一个函数的声明
//例如:Person p1();不会认为在创建对象*/
//Person p2(10);//有参构造函数调用
//Person p3(p2);//拷贝构造函数调用
//cout << "p2的年龄为" << p2.age << endl;
//cout << "p3的年龄为" << p3.age << endl;
//显示法
//Person p1;//无参
//Person p2 = Person(10);//有参
//Person p3 = Person(p2);//拷贝
如果把等号右边的式子单独拿出来
Person(10)这是一个匿名对象-特点——当前行执行结束后,系统会立即回收掉匿名对象
注意:不要利用拷贝函数初始化匿名对象,比如Person(p3),编译器会认为Person(p3)等价于 Person p3 编译器会认为是对象的声明
//隐式转换法
Person p4 = 10;//相当与Person p4 = Person(10);
Person p6={9,"张三"};//多个参数的隐式转换法,用大括号括起来,C++11
Person p5 = p4;//拷贝构造
system("pause");
return 0;
}
#### 拷贝构造函数调用时机
C++中拷贝构造函数调用时机通常有三种情况
- 使用一个已经创建完毕的对象来初始化一个新对象
- 值传递的方式给函数参数传值
- 以值方式返回局部对象
```c++
#include<iostream>
using namespace std;
class Person
{
public:
Person()
{
cout << "Person的默认构造函数调用" << endl;
}
Person(int age)
{
cout << "Person的有参构造函数调用" << endl;
m_Age = age;
}
Person(const Person& p)
{
cout << "Person的拷贝构造函数调用" << endl;
m_Age = p.m_Age;
}
~Person()
{
cout << "Person的析构函数调用" << endl;
}
int m_Age;
};
//使用一个已经创建完毕的对象来初始化一个对象
void test01()
{
Person p1(20);
Person p2(p1);
cout << "p2的年龄为" << p2.m_Age << endl;
}
//值传递的方式给函数参数传值,如果实参是引用对象,则不会发生拷贝
void dowork(Person p)
{
}
void test02()
{
Person p;
dowork(p);
}
//值方式返回局部对象,而且不是引用类型,此时会拷贝
Person dowork2()
{
Person p1;
cout << (int*)&p1 << endl;
return p1;
}
void test03()
{
Person p = dowork2();
cout << (int*)&p << endl;
}
//对象数组的初始化列表,会调用拷贝构造函数
Person f1,f2,f3,f4;
Person F4[4]={f1,f2,f3,f4};//把f1拷贝给F4的第一个成员,f2拷贝给F4的第二个成员,以此类推
int main(void)
{
//test01();
//test02();
test03();
system("pause");
return 0;
}
注意(奇牛)
Person f1;
Person f2=f1;//创建f2对象的时候用f1的值来初始化f2,这时会调用拷贝构造函数,此时若后续更改f1的值,不会影响f2的值
换种形式
Person f1,f2;
f2=f1;//在创建之后,再把f1赋值给f2,此时会自动调用赋值构造函数,如果没有定义赋值构造函数,编译器会自动生成一个赋值构造函数,像这种自动生成的都是浅拷贝
4.2.3 构造函数的调用规则
默认情况下,C++编译器至少给一个类添加三个函数
默认构造函数(无参、函数体为空)
默认析构函数(无参、函数体为空)
默认拷贝函数构造函数,对属性值拷贝
构造函数调用规则如下:
如果用户定义有参构造函数,C++不再提供默认无参构造,但是会提供默认拷贝构造
如果用户定义拷贝构造函数,C++不会再提供其他构造函数
4.2.4 深拷贝与浅拷贝
深浅拷贝是面试的一个经典的问题,也是常见的一个坑。
浅拷贝:简单的赋值拷贝操作。
深拷贝:在堆区中重新申请空间,进行拷贝操作。
浅拷贝带来的问题——内存重复释放
浅拷贝的这个问题需要用深拷贝来解决
重新在堆区找一块内存来存放他。
自己实现拷贝构造函数来解决浅拷贝带来的问题
解决:
深拷贝——手动创建拷贝构造函数。
4.2.5 初识化列表
作用:
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 test()
{
//Person p(10,20,30);
Person p(30,20,10);
cout << p.m_A << endl;
cout << p.m_B << endl;
cout << p.m_C << endl;
}
int main(void)
{
test();
system("pause");
return 0;
}
4.2.6 类对象作为类成员
C++中类的成员可以是另一个类的对象,我们称该成员为对象成员。
例如:
class A{}class B{ A a;}
B类中有对象A作为成员,A为对象成员。
那么当创建B对时,A与B的构造和析构的顺序是怎么样的
A先被构造
当其他类的对象作为本类的成员时,构造时先构造其他类的对象,再构造自身。
析构呢?与构造函数相反。
自身的析构函数先进行,之后其它类再进行。
#include<iostream>
#include<string>
using namespace std;
class Phone
{
public:
Phone(string p)
{
Phonename = p;
cout << "Phone的构造函数调用" << endl;
}
~Phone()
{
cout << "Phone的析构函数调用" << endl;
}
string Phonename;
};
class Person
{
public:
//Phone Personphone = pname 隐式转换法
Person(string name, string pname):Personname(name), Personphone(pname)
{
cout << "Person的构造函数调用" << endl;
}
~Person()
{
cout << "Person的析构函数调用" << endl;
}
string Personname;
Phone Personphone;
};
void test()
{
Person p("张三", "华为");
cout << p.Personname<< endl;
cout << p.Personphone.Phonename<< endl;
}
int main(void)
{
test();
system("pause");
return 0;
}
4.2.7 静态成员
静态成员就是在成员变量和成员函数前面加上关键字啊static,称为静态成员。
静态成员分为:
- 静态成员变量
- 所有对象共享同一份数据
- 在编译阶段分配内存
- 类内声明,类外初始化
- 静态成员函数
- 所有成员共享同一个函数
- 静态成员函数只能访问静态成员变量
#include<iostream>
using namespace std;
class Person
{
public:
static int age;
}
void test01()
{
Person p;
cout<<p.age<<endl;
}
//运行失败,失败原因,没有在类外初始化,初始化的工作必须要做
#include<iostream>
using namespace std;
class Person
{
public:
static int age;
}
int Person::age=30;//类外初始化
void test01()
{
Person p;
cout<<p.age<<endl;
}
//eg.
class person
{
public:
static int a;//类内声明
};
int person::a = 100;//类外初始化
int main()
{
person p1;
cout << "p1的值为:" << p1.a << endl;//输出结果为100
person p2;
p2.a = 200;
cout << "p1的值为:" << p1.a << endl;//输出结果为200,所有对象共享同一份数据,所以p2修改a的值,p1访问a的值也会跟着改变
return 0;
}
注意:
① 静态成员变量不属于某一个对象。因此有两种访问方式:①类名访问,②对象访问。
class person
{
public:
static int a;
};
int person::a = 100;
int main()
{
//对象访问
person p1;
cout << p1.a << endl;
//类名访问
cout << person::a << endl;
return 0;
}
②静态成员变量也有访问权限。
静态成员函数:
🔵特点:
①所有对象共享一个函数。
②静态成员函数只能访问静态成员变量。
🔴注意:静态成员函数也有访问权限。
//静态成员函数的访问
class person
{
public:
static void test()
{
cout << "static void test()调用" << endl;
}
};
int main()
{
//对象访问
person p;
p.test();
//成员访问
person::test();
return 0;
}
//静态成员函数只能访问静态成员函数
class person
{
public:
static void test()
{
a = 200;
b = 200;//err,对象不明
cout << "static void test()调用" << endl;
}
static int a;//静态成员函数访问静态成员变量
int b;//非静态成员函数
};
int person::a = 100;
int main()
{
person p;
p.test();
return 0;
}
4.3 C++对象模型和this指针
4.3.1 成员变量和成员函数分开存储
在C++中,类的成员变量和成员函数分开存储,只有非静态成员变量才属于类的对象上。
//eg.
class person1
{
};
class person2
{
int a;//非静态成员变量
};
class person3
{
int a;
static int b;//静态成员变量
};
class person4
{
int a;
static int b;//静态成员变量
void test()//非静态成员函数
{
}
};
int main()
{
//空对象占用内存是 1
//C++会给每一个空对象分配一个字节的内存空间,为了区分空对象占内存的位置
//每一个空对象也应该有一个独一无二的内存地址
person1 p1;
cout << "sizeof(p)=" << sizeof(p1) << endl;//1
//虽然空对象有一个字节,但是一旦类里面不为空就跟着类中字节走
person2 p2;
cout << "sizeof(p)=" << sizeof(p2) << endl;//4
//静态成员变量不属于类对象上的
person3 p3;
cout << "sizeof(p)=" << sizeof(p3) << endl;//4
//类的成员变量和成员函数分开存储
person4 p4;
cout << "sizeof(p)=" << sizeof(p4) << endl;//4
return 0;
}
4.3.2 this指针概念
通过上一个知识点《成员变量和成员函数是分开存储的》我们知道C++中成员变量和成员函数是分开存储的。
每一个非静态成员函数只会诞生一份函数实例,也就是说多个同类型的对象会共用一块代码。
那么问题是:这一块代码是如何区分是哪个对象调用自己的呢?
C++通过提供特殊的对象指针,this指针,解决上述问题。
this指针指向被调用的成员函数所属的对象。
(谁调的,this就指向谁)
his指针是隐含每个非静态成员函数内的一种指针。
this指针不需要定义,直接使用即可。
this指针的用途
- 当形参和成员变量同名时,可用this指针来区分
- 在类的非静态成员函数中返回对象本身,可使用return *this
#include<iostream>
using namespace std;
class Person
{
public:
Person(int age)
{
//this指针指向的是被调函数的成员函数所属的对象
//这里指向的就是p
this->age = age;
}
//返回本体要用引用的方式进行返回
//这里返回值如果是Person,就创建了一个新的对象
Person& PersonAddPerson(Person &p)
{
this->age += p.age;
return *this;//this是指向p2的指针,*this就是p2这个对象的本体
}
int age;//注意起名规范也可以解决名字冲突的问题
};
//解决对象冲突
void test()
{
Person p(18);
cout << p.age << endl;
}
//返回对象本身用*this
void test01()
{
Person p1(10);
Person p2(10);
p2.PersonAddPerson(p1);//将p1和p2的加在一起
//多次追加,return *this;
//链式编程思想
p2.PersonAddPerson(p1).PersonAddPerson(p1);
cout << p2.age << endl;
}
int main(void)
{
test01();
system("pause");
return 0;
}
4.3.3 空指针访问成员函数
C++中空指针可以调用成员函数,但是要注意有没有用到this指针,如果用到this指针,需要加以判断保证代码的健壮性。
class person
{
public:
void test1()
{
cout << "test1" << endl;
}
void test2()
{
cout << "age="<<age<< endl;//err 一般在属性的前面都会默认加上this->,但是传入的指针为空,无法访问里面的属性
}
int age;
};
int main()
{
person *p=NULL;
p->test1();//可以正常运行
p->test2();//异常
return 0;
}
void test2()
{
if(this->age==NULL)
return;//提高代码的健壮性
cout << "age="<<this->age<< endl;//err,传入的指针为空
}
4.3.4 const修饰成员函数
常函数:
- 成员函数后加const后我们称这个函数为常函数
- 常函数不可以修改成员属性
- 成员属性声明时加关键字mutable后,在常函 数中依然可以修改
常对象:
- 声明对象前const称该对象为常对象。
- 常对象只能调用常函数。
#include<iostream>
using namespace std;
//常函数
class Person
{
public:
//this指针的本质是指针常量,指针的指向是不可以修改的
//就相当于Person *const this;
//在成员函数后面加const修饰的是this指向,让指针指向的值也不可以修改
void showPerson1()
{
this->m_b = 100;//this指针指向的值可以修改
this = NULL; //this指针是不可以修改指针的指向的
}
void showPerson() const//加个const,this指针指向的值也不可以修改了,
相当于const Person *const this;
{
this->m_b = 100;//异常
//this = NULL;this指针是不可以修改指针的指向的
}
int m_a;
mutable int m_b;//加了mutable修饰的特殊变量,即使在常函数,常对象中,也可以修改这个值
void func()
{
m_a = 100;//在普通成员函数中是可以修改的
}
};
void test()
{
Person P;
P.showPerson();
}
//常对象
void test1()
{
const Person p;//在对象前加const,变为常对象
//p.m_a = 100;//异常,常对象的属性不允许被修改
p.m_b = 100;//正常,加了mutable修饰的特殊变量,允许在常对象中修改这个值
//常对象只能调用常函数
p.showPerson();
//p.func();常对象不能调用普通成员函数,因为普通成员函数可以修改属性。
}
int main(void)
{
test();
system("pause");
return 0;
}
奇牛
const数据成员的初始化方式:
- 使用类内值(C++11支持)
- 使用构造函数的初始化列表
(如果同时使用这两种方式,以初始化列表中的值为最终初始化结果)
注意: 不能在构造函数或其他成员函数内,对const成员赋值!
#pragma once
......
class Human {
public:
......
private:
......
const string bloodType='B';//C++11才支持
};
// 使用初始化列表,对const数据成员初始化
Human::Human():bloodType("未知") {
......
//在成员函数内,不能对const数据成员赋值
bloodType = "未知血型";(异常)
count++;
}
4.4 友元
可客厅就是Public,你的卧室就是Private
客厅所有人都可以进去,但是你的卧室只有和你亲密的人可以进。
在程序中,有些私有属性也想让类外特殊的一些函数或者类进行访问,就需要用到友元技术。
友元的目的就是让一个函数或者类 访问另一个类中的私有元素。
友元的关键字——friend
友元的三种实现
- 全局函数做友元
- 类做友元
- 成员函数做友元
全局函数做友元
就是将此函数在类的最上面写一个声明,前面加一个friend。
#include<iostream>
#include<string>
using namespace std;
class Building
{
//goodgay全局函数是Building类的一个好朋友,可以访问你家的卧室(私有成员)
friend void goodgay(Building* building);
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;
}
void test()
{
Building building;
goodgay(&building);
}
int main(void)
{
test();
system("pause");
return 0;
}
类做友元:让一个类可以访问另一个类中的私有成员
#include<iostream>
#include<string>
using namespace std;
//在前面先声明一下
class Building;
class GoodGay
{
public:
GoodGay();
void visit();//参观函数 访问Building中的属性
Building* building;
};
class Building
{
//GoodGay是Building类的好朋友,可以访问其私有属性
friend class GoodGay;
public:
Building();
public:
string m_SittingRoom;
private:
string m_BedRoom;
};
//在类外写成员函数
Building::Building()
{
m_SittingRoom = "客厅";
m_BedRoom = "卧室";
}
GoodGay::GoodGay()
{
//创建一个Building对象
building = new Building;
}
void GoodGay::visit()
{
cout << "好基友正在访问你的" << building->m_SittingRoom << endl;
cout << "好基友正在访问你的" << building->m_BedRoom << endl;
}
void test()
{
GoodGay gy;
gy.visit();
}
int main(void)
{
test();
system("pause");
return 0;
}
成员函数做友元
告诉编译器 另一个类中的xx成员函数作为本类的好朋友,可以访问私有函数。
#include<iostream>
#include<string>
using namespace std;
class Building;
class GoodGay
{
public:
GoodGay();
void visit();//可以访问Building中私有成员
void visit1();//不可以访问Building中私有成员
Building* builidng;
};
class Building
{
//告诉编译器 GoodGay类中的visit成员函数作为本类的好朋友,可以访问私有函数
friend void GoodGay::visit();
public:
Building();
public:
string m_SittingRoom;
private:
string m_BedRoom;
};
Building::Building()
{
m_SittingRoom = "客厅";
m_BedRoom = "卧室";
}
GoodGay::GoodGay()
{
builidng = new Building;
}
void GoodGay::visit()
{
cout << "visit正在访问" << builidng->m_SittingRoom << endl;
cout << "visit正在访问" << builidng->m_BedRoom << endl;
}
void GoodGay::visit1()
{
cout << "visit1正在访问" << builidng->m_SittingRoom << endl;
}
void test()
{
GoodGay gg;
gg.visit();
gg.visit1();
}
int main(void)
{
test();
system("pause");
return 0;
}
4.5 运算符重载
注意事项
4.5.1 加号运算符重载
作用:实现两个自定义数据类型相加的运算。
例如:两个整型相加编译器知道该怎么进行运算,如果是两个自定义出来的类型,两个Person想加,编译器就不知道该怎么运算了。
#include<iostream>
#include<string>
using namespace std;
//加号运算符重载
class Person
{
public:
//1.成员函数重载+
/*Person operator+(Person& p)
{
Person temp;
temp.m_A = this->m_A + p.m_A;
temp.m_B = this->m_B + p.m_B;
return temp;
}*/
int m_A;
int m_B;
};
//2.全局函数重载+
Person operator+(Person& p1, 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+(Person& p1, int num)
{
Person temp;
temp.m_A = p1.m_A + num;
temp.m_B = p1.m_B + num;
return temp;
}
void test01()
{
Person p1;
p1.m_A = 10;
p1.m_B = 10;
Person p2;
p2.m_A = 10;
p2.m_B = 10;
//成员函数重载本质调用
//Person p3 = p1.operator+(p2);
//Person p3 = p1 + p2;//可以简化成这种形式
//全局函数重载的本质调用
//Person p3 = operator+(p1,p2);
/*cout << p3.m_A << endl;
cout << p3.m_B << endl;*/
//运算符重载也可以发生函数重载
Person p3 = p1 + 10;
cout << p3.m_A << endl;
cout << p3.m_B << endl;
}
int main(void)
{
{
test01();
system("pause");
return 0;
}
总结:
- 对于内置的数据类型的表达式的运算符是不可能改变的
- 不要滥用运算符重载
4.5.2左移运算符重载
#include<iostream>
using namespace std;
class Person
{
friend ostream& operator<<(ostream& cout, Person& p);
public:
Person(int a, int b)
{
m_A = a;
m_B = b;
}
//利用成员函数重载左移运算符p.operator<<(cout)简化版本p<<cout
//一般我们不会利用成员函数来重载<<运算符,以为无法实现cout在左边
/*void operator<<(ostream &cout)
{
cout << p.m_A << endl;
cout << p.m_B << endl;
}*/
private:
int m_A;
int m_B;
};
//只能利用全局函数来重载左移运算符
ostream& operator<<(ostream &cout, Person &p) //这样写的本质就是operator<<(cout,p)简化版本就是cout<<p;
{
cout << p.m_A << endl;
cout << p.m_B << endl;
return cout;
}
void test()
{
Person p(10,10);
cout << p << "hello world" << endl;
}
int main(void)
{
test();
system("pause");
return 0;
}
4.5.3 关系运算符重载
作用:重载关系运算符,可以让两个自定义类型对象进行对比操作
#include<iostream>
#include<string>
using namespace std;
class Person
{
public:
//重载==
bool operator==(Person &p)
{
if (this->m_Name == p.m_Name && this->m_Age == p.m_Age)
{
return true;
}
else
{
return false;
}
}
bool operator!=(Person &p)
{
if (this->m_Name == p.m_Name && this->m_Age == p.m_Age)
{
return false;
}
else
{
return true;
}
}
Person(string name, int age)
{
m_Name = name;
m_Age = age;
}
string m_Name;
int m_Age;
};
void test()
{
Person p1("张三", 20);
Person p2("张三", 20);
if (p1 == p2)
{
cout << "p1和p2是相等的" << endl;
}
else
{
cout << "p1和p2是不相等的" << endl;
}
if (p1 != p2)
{
cout << "p1和p2是不相等的" << endl;
}
else
{
cout << "p1和p2是相等的" << endl;
}
}
int main(void)
{
test();
system("pause");
return 0;
}
4.5.4 函数调用运算符重载
- 函数调用运算符()也可以重载
- 由于重载后使用的方式非常像函数的调用,因此称为仿函数
- 仿函数没有固定写法,非常灵活
#include<iostream>
#include<string>
using namespace std;
//函数调用运算符重载
class MyPrint
{
public:
//重载函数调用运算符
void operator()(string text)
{
cout << text << endl;
}
};
class MyAdd
{
public:
int operator()(int a, int b)
{
return a + b;
}
};
void test()
{
MyPrint myprint;
myprint("hello world");
MyAdd myadd;
cout << myadd(1, 2) << endl;
//匿名函数对象——特点:当前行被执行完立即释放
cout << MyAdd()(100,100) << endl;
}
int main(void)
{
test();
system("pause");
return 0;
}
4.5.5 赋值运算符重载
C++编译器至少给一个类添加4个函数(前三个之前已经讲过了)
- 默认构造函数(无参,函数体为空)
- 默认析构函数(无参,函数体为空)
- 默认拷贝构造函数,对属性进行值拷贝
- 赋值运算符operator=,对属性进行值拷贝
如果类中有属性指向堆区,做赋值操作时也会出现深浅拷贝问题。
#include<iostream>
using namespace std;
class Person
{
public:
Person(int age)
{
m_Age = new int(age);
}
~Person()
{
if (m_Age != NULL)
{
delete m_Age;
m_Age = NULL;
}
}
//重载赋值运算符
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;
};
void test1()
{
Person p1(18);
Person p2(20);
Person p3(30);
p3 = p2 = p1;
cout << *(p1.m_Age) << endl;
cout << *(p2.m_Age) << endl;
cout << *(p3.m_Age) << endl;
}
int main(void)
{
test1();
system("pause");
return 0;
}
4.5.6 递增运算符重载
实现下图自增的功能
#include<iostream>
using namespace std;
//重载递增运算符
class MyInteger
{
friend ostream& operator<<(ostream& cout, MyInteger myint);
public:
MyInteger()
{
m_Num = 0;
}
//重载++运算符——前置
//返回引用是为了一直对一个数据进行递增操作
MyInteger& operator++()
{
++m_Num;
return *this;
}
//重载++运算符——后置
MyInteger operator++(int)//这个int在这里作为占位参数,用来区分前置递增和后置递增
{
MyInteger temp = *this;
m_Num++;
return temp;
//后置递增要返回值,因为如果返回引用,这里相当于返回的是一个局部对象的引用。
//局部对象在当前函数执行完毕之后就被释放掉了,还要返回引用就是非法操作。
}
private:
int m_Num;
};
//全局函数重载左移运算符
ostream& operator<<(ostream& cout, MyInteger myint)
{
cout << myint.m_Num << endl;
return cout;
}
void test()
{
MyInteger myint;
cout << ++(++myint);
cout <<myint;
}
void test02()
{
MyInteger myint;
cout << myint++ << endl;
cout << myint << endl;
}
int main(void)
{
//test();
test02();
system("pause");
return 0;
}
4.6继承
父类的构造函数和析构函数无法被继承
4.6.1 继承方式
#include<iostream>
using namespace std;
//公共继承
class Base1
{
public:
int m_A;
protected:
int m_B;
private:
int m_C;
};
class Son1 :public Base1
{
public:
void func()
{
m_A = 10;//父类中的公共权限成员,到了子类中依然是公共权限
m_B = 20;//父类中的保护权限成员,到了子类中依然是保护权限
//m_C = 10;父类中的隐私权限成员,子类访问不到
}
};
void test01()
{
Son1 son1;
son1.m_A = 100;
//son1.m_B = 100;保护权限的内容到了类外就无法访问了
};
//保护继承
class Base2
{
public:
int m_A;
protected:
int m_B;
private:
int m_C;
};
class Son2 :protected Base2
{
void func()
{
m_A = 100;//父类中公共权限的成员,因为是保护继承,到子类中变为保护权限
m_B = 100;//父类中保护权限的成员,保护继承后到了子类还是保护权限。
//m_C = 100;父类中的私有成员子类访问不到
}
};
void test02()
{
Son2 son2;
//保护权限类外访问不到,所以在son2中m_A也访问不到了
}
//私有继承
class Base3
{
public:
int m_A;
protected:
int m_B;
private:
int m_C;
};
class Son3:private Base3
{
void func()
{
m_A = 100;//父类中公共成员,私有继承后,到了子类变为私有成员
m_B = 100;//父类中保护成员,私有继承后,到了子类变为私有成员
//m_C = 100;父类的私有权限成员仍然访问不到
}
};
void test03()
{
Son3 son3;
//私有成员类外访问不到
}
//验证Son3私有继承后成员是否变成了私有属性
class GrandSon3 :public Son3
{
void func()
{
//访问不到父类的私有成员
//到了Son3中m_A,m_B,m_C全是私有成员,子类无法访问
}
};
int main(void)
{
system("pause");
return 0;
}
4.6.2 继承中的对象模型
问题:从父类继承过来的对象,哪些属于子类对象?
父类中所有的非静态成员属性都会被子类继承下去。
父类中私有的成员属性是被编译器给隐藏了,因此访问不到,但是确实被继承下去了
#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 test01()
{
//父类中所有的非静态成员属性都会被子类继承下去
//父类中私有的成员属性是被编译器给隐藏了,因此访问不到,但是确实被继承下去了
cout << "sizeof of son:" << sizeof(Son) << endl;//结果是16 = 12 + 4
}
int main(void)
{
test01();
system("pause");
return 0;
}
4.6.3 继承中构造和析构的顺序
子类继承父类后,当创建子类时,也会调用父类的构造函数。
问题:父类和子类的构造函数和析构顺序怎么样的呢?
先构造父类,再构造子类
先析构子类,再析构父类
创建子类对象的同时也会创建一个父类对象。
先调用父类构造函数,用来初始化从父类继承的数据
再调用自己的构造函数,用来初始化自己定义的数据
如果没有在子类体现父类的构造函数,那么就会自动调用父类的默认构造函数
如果父类没有写默认构造函数,那么就会编译错误
#include <iostream>
using namespace std;
class Father
{
public:
Father(const char* name, int age)
{
this->name = name;
this->age = age;
}
~Father()
{
}
private:
int age;
string name;
};
class Son :public Father
{
public:
//子类构造函数的参数name,age去调用父类的有参构造函数
Son(const char* name, int age,const char* game):Father(name,age)
{
this->game = game;
}
~Son()
{
}
private:
string game;
};
int main()
{
Father wjl("王健林", 68);
Son wsc("王思聪", 68,"王者荣耀");
}
当有其他类的对象作为本类的数据成员,且本类继承了某个类
4.6.4 继承同名成员处理方式
问题:当子类与父类出现同名的成员。如何通过子类对象,访问到子类或父类中同名的数据呢?
- 访问子类同名成员,直接访问即可
- 访问父类同名成员,需要加作用域
#include<iostream>
using namespace std;
class Base
{
public:
Base()
{
m_A = 100;
}
void func()
{
cout << "父类同名成员函数调用" << endl;
}
void func(int a)
{
cout << "父类同名重载成员函数调用" << endl;
}
int m_A;
};
class Son:public Base
{
public:
Son()
{
m_A = 200;
}
void func()
{
cout << "子类同名成员函数调用" << endl;
}
int m_A;
};
//同名成员属性处理方式
void test01()
{
Son son;
cout <<son.m_A<< endl;
//如果要通过子类对象访问到父类中的同名成员,需要加作用域。
cout <<son.Base::m_A<< endl;
}
//同名成员函数处理方式
void test02()
{
Son son1;
son1.func();//子
son1.Base::func();//父
//如果子类中出现和父类同名的成员函数
//子类的同名成员会隐藏掉父类中所有同名成员函数
//如果想要访问到父类中被隐藏的同名成员函数,需要加作用域
son1.Base::func(10);
}
int main(void)
{
test02();
system("pause");
return 0;
}
总结:
- 子类对象可以直接访问到子类中同名成员
- 子类对象加作用域可以访问到父类同名成员
- 当子类与父类拥有同名的成员函数,子类会隐藏父类中同名成员函数,加作用域可以访问到父类同名函数。
4.6.5 继承同名静态成员处理方式
问题:继承中同名的静态成员在子类对象上是如何进行访问的呢?
静态成员和非静态成员出现同名,处理方式 一致。
- 访问子类同名成员,直接访问即可
- 访问父类同名成员,需要加作用域
#include<iostream>
using namespace std;
class Base
{
public:
static void func()
{
cout << "父类静态成员函数调用" << endl;
}
static void func(int a)
{
cout << "父类静态成员重载函数调用" << endl;
}
static int m_A;
};
int Base::m_A = 100;
class Son :public Base
{
public:
static void func()
{
cout << "子类静态成员函数调用" << endl;
}
static int m_A;
};
int Son::m_A = 200;
//同名静态成员
void test()
{
//通过对象访问
Son son1;
cout << "通过对象访问" << endl;
cout << son1.m_A << endl;
cout << son1.Base::m_A << endl;
//通过类名访问
cout << "通过类名访问" << endl;
cout << Son::m_A << endl;
//第一个::代表通过类名方式访问,第二个::代表访问父类作用域下
cout << Son::Base::m_A << endl;
}
//同名静态函数
void test01()
{
//通过对象访问
Son son2;
cout << "通过对象访问" << endl;
son2.func();
son2.Base::func();
//通过类名访问
cout << "通过类名访问" << endl;
Son::func();
Son::Base::func();
//父类同名重载成员函数调用
//子类出现和父类同名的静态成员函数,也会隐藏掉父类中所有同名成员函数(重载)
//如果想访问父类中被隐藏的同名成员,需要加作用域
Son::Base::func(100);
}
int main(void)
{
test();
cout << "我是分割线------" << endl;
test01();
system("pause");
return 0;
}
总结:同名静态成员处理方式和非静态处理方式一样,只不过有两种访问的方式(通过对象和类名)。
4.6.6 多继承语法
C++允许一个类继承多个类
语法:
class 子类:继承方式 父类1,继承方式 父类2
多继承可能会引发父类中有同名成员出现,需要加作用域区分
C++实际开发中不建议使用多继承
#include<iostream>
using namespace std;
//多继承语法
class Base1
{
public:
Base1()
{
m_A = 100;
}
int m_A;
};
class Base2
{
public:
Base2()
{
m_A = 200;
}
int m_A;
};
//子类需要继承base1和base2
class Son:public Base1,public Base2
{
public:
Son()
{
m_C = 300;
m_D = 400;
}
int m_C;
int m_D;
};
void test01()
{
Son son1;
cout << sizeof(son1) << endl;//16
cout << "第一个父类的m_A:" << son1.Base1::m_A<<endl;
cout << "第二个父类的m_A:" << son1.Base2::m_A<<endl;
}
int main(void)
{
test01();
system("pause");
return 0;
}
(奇牛)多继承的使用,构造函数调用顺序
#include <iostream>
using namespace std;
#include <string>
class Father
{
public:
Father(const char* lastName="无姓", const char* firstName="无名")
{
this->lastName = lastName;
this->firstName = firstName;
}
~Father()
{
}
void playBasketball()
{
cout << "打篮球" << endl;
}
protected:
string lastName;
string firstName;
};
class Mother
{
public:
Mother(const char* food ,const char* lastName = "无姓", const char* firstName = "无名")
{
this->food = food;
this->lastName = lastName;
this->firstName = firstName;
}
~Mother()
{
}
void dance ()
{
cout << "跳舞" << endl;
}
private:
string lastName;
string firstName;
string food;
};
class Son :public Father,public Mother
{
public:
//子类构造函数的参数name,age去调用父类的有参构造函数
Son(const char* food, const char* lastName, const char* firstName,const char* game):Father(lastName,firstName),Mother(food)
{
this->game = game;
}
~Son()
{
this->game = game;
}
void playgame()
{
cout << "玩游戏" << endl;
}
private:
string game;
};
int main()
{
Son wsc("川菜", "王", "思聪", "吃鸡");
wsc.dance();
wsc.playBasketball();
wsc.playgame();
system("pause");
return 0;
}
取决于这里的顺序
(奇牛)多继承二义性问题
#include <iostream>
using namespace std;
#include <string>
class Father
{
public:
Father(const char* lastName="无姓", const char* firstName="无名")
{
this->lastName = lastName;
this->firstName = firstName;
}
~Father()
{
}
void playBasketball()
{
cout << "打篮球" << endl;
}
void dance()
{
cout << "父亲跳舞" << endl;
}
protected:
string lastName;
string firstName;
};
class Mother
{
public:
Mother(const char* food ,const char* lastName = "无姓", const char* firstName = "无名")
{
this->food = food;
this->lastName = lastName;
this->firstName = firstName;
}
~Mother()
{
}
void dance ()
{
cout << "母亲跳舞" << endl;
}
private:
string lastName;
string firstName;
string food;
};
class Son :public Father,public Mother
{
public:
//子类构造函数的参数name,age去调用父类的有参构造函数
Son(const char* food, const char* lastName, const char* firstName,const char* game):Father(lastName,firstName),Mother(food)
{
this->game = game;
}
~Son()
{
this->game = game;
}
void playgame()
{
cout << "玩游戏" << endl;
}
void dance()
{
Father::dance();
Mother::dance();
cout << "儿子跳舞" << endl;
}
private:
string game;
};
int main()
{
Son wsc("川菜", "王", "思聪", "吃鸡");
//如何解决二义性问题
//1.使用"类名::"进行指定,指定调用从哪个基类继承的方法
wsc.Father::dance();
wsc.Mother::dance();
//2.在子类中重新实现这个同名方法,并在这个方法内部,可以使用基类名
//进行限定,来调用对应的基类方法,也可以加上自己的需求
wsc.dance();
wsc.playBasketball();
wsc.playgame();
system("pause");
return 0;
}
4.6.7 子类型关系
#include <iostream>
using namespace std;
class A
{
public:
A(){}
~A(){}
void kill()
{
cout << "A kill" << endl;
}
};
class B :public A
{
public:
B(){}
~B(){}
void kill()
{
cout << "B kill" << endl;
}
};
void test1(A a)
{
a.kill();//调用的是A类对象的kill方法
}
void test2(B b)
int main()
{
A a;
test1(a);//输出结果: A kill
B b;
test1(b);//替父从军 输出结果:A kill,与test(a)效果一样
//反过来不可以
test2(a);//错误
}
第一条,此时执行f->play(),调用的是父类的方法,输出结果是KTV唱歌
第二条,此时执行f2.play(),调用的是父类的方法,输出结果是KTV唱歌
4.6.8 菱形继承,虚继承,虚基类
#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 test01()
{
SheepTuo st;
st.Sheep::m_Age = 18;
st.Tuo::m_Age = 28;
//当菱形继承,当两个父类拥有相同的数据,需要加作用域来区分
cout << st.Sheep::m_Age << endl;
cout << st.Tuo::m_Age << endl;
cout << st.m_Age << endl;
//这份数据我们知道,只有一份就可以了,菱形继承导致数据有两份,资源浪费
}
int main(void)
{
test01();
system("pause");
return 0;
}
4.7 多态
4.7.1 多态的基本概念
多态分为两种
- 静态多态:函数重载和运算符重载属于静态多态,复用函数名
- 动态多态:派生类和虚函数实现运行时多态
静态多态和动态多态的区别
- 静态多态的函数地址早绑定 - 编译阶段确定函数地址
- 动态多态的函数地址晚绑定 - 运行阶段确定函数地址
#include<iostream>
using namespace std;
class Animal
{
public:
//加上virtual变成虚函数,实现地址晚绑定
virtual void speak()
{
cout << "动物在说话"<< endl;
}
};
class Cat :public Animal
{
public:
void speak()
{
cout << "小猫在说话" << endl;
}
};
class Dog : public Animal
{
public:
void speak()
{
cout << "小狗在说话" << endl;
}
};
//执行说话的函数
//地址早绑定,在编译阶段就确定函数地址
//如果想让猫说话,那么这个函数的地址就不能提前绑定,需要在运行阶段进行绑定
//动态多条满足条件
/*
1.有继承关系
2.子类重写父类的虚函数
*/
//重写要求:函数返回值类型 函数名 参数列表 完全相同
//动态多态的使用
/*
父类的指针或者引用 指向子类的对象//Animal &animal = cat;
*/
void doSpeak(Animal &animal)//Animal &animal = cat;
{
animal.speak();
}
void test01()
{
Cat cat;
doSpeak(cat);
Dog dog;
doSpeak(dog);
}
int main(void)
{
test01();
system("pause");
return 0;
}
总结:
多态满足条件
- 有继承关关系
- 子类重写父类中的虚函数
多态的使用条件
- 父类指针或引用指向子类对象
重写:函数返回值类型 函数名 参数列表 完全一致称为重写
#include <iostream>
using namespace std;
class Animal
{
public:
void speak()
{
cout << "动物在说话" << endl;
}
};
class Cat
{
public:
virtual void speak()
{
cout << "动物在说话" << endl;
}
};
int main()
{
cout<<sizeof(Animal);//非静态成员函数不属于类的对象上,所以是个空类,空类的大小是1
cout << sizeof(Cat);//输出结果是4,内部有虚函数指针,指针的大小是4
}
奇牛
//在没有运用虚函数时,执行结果是
到KTV唱歌...
到KTV唱歌...
到KTV唱歌...
#include <iostream>
using namespace std;
class Father {
public:
void play() {
cout << "到KTV唱歌..." << endl;
}
};
class Son :public Father {
public:
void play() {
cout << "一起打王者吧!" << endl;
}
};
void party(Father **men, int n) {
for (int i = 0; i<n; i++) {
men[i]->play();
}
}
int main(void) {
Father father;
Son son1, son2;
Father* men[] = { &father, &son1, &son2 };
party(men, sizeof(men) / sizeof(men[0]));
system("pause");
return 0;
}
#include <iostream>
using namespace std;
class Father {
public:
void play() {
cout << "到KTV唱歌..." << endl;
}
};
class Son :public Father {
public:
void play() {
cout << "一起打王者吧!" << endl;
}
};
void party(Father **men, int n) {
for (int i = 0; i<n; i++) {
men[i]->play();
}
}
int main(void) {
Father father;
Son son1, son2;
Father* men[] = { &father, &son1, &son2 };
party(men, sizeof(men) / sizeof(men[0]));
system("pause");
return 0;
}
多态的本质:
形式上,使用统一的父类指针做一般性处理,
但是实际执行时,这个指针可能指向子类对象,
形式上,原本调用父类的方法,但是实际上会调用子类的同名方法。
【注意】
程序执行时,父类指针指向父类对象,或子类对象时,在形式上是无法分辨的!
只有通过多态机制,才能执行真正对应的方法。
虚函数的定义:
在函数的返回类型之前使用virtual
只在成员函数的声明中添加virtual, 在成员函数的实现中不要加virtual
虚函数的继承:
- 如果某个成员函数被声明为虚函数,那么它的子类【派生类】,以及子类的子类中,所继承的这个成员函数,也自动是虚函数。
- 如果在子类中重写这个虚函数,可以不用再写virtual, 但是仍建议写virtual, 更可读!
多态的原理
#include <iostream>
using namespace std;
class Father {
public:
virtual void func1() { cout << "Father::func1" << endl; }
virtual void func2() { cout << "Father::func2" << endl; }
virtual void func3() { cout << "Father::func3" << endl; }
void func4() { cout << "非虚函数:Father::func4" << endl; }
public: //为了便于测试,特别该用public
int x = 100;
int y = 200;
static int z;
};
int main()
{
Father father;
//输出结果是12,不管有几个虚函数,只存了一个虚函数表指针,指向一个虚函数表,
//另外x,y各占四个字节,z和func3不属于类的对象上,不占用空间
cout << "sizeof(father)==" << sizeof(father) << endl;
}
纯虚函数和抽象类
在多态中,通常父类汇中虚函数的实现是毫无意义的,主要都是调用子类重写的内容。
因此可以将虚函数改为纯虚函数。
纯虚函数语法virtual 返回值类型 函数名 (参数列表) = 0;
当类中有了纯虚函数,这个类也称为抽象类。
抽象类特点:
无法实例化对象
子类必须重写抽象类中的纯虚函数,否则也属于抽象类
#include<iostream>
using namespace std;
//纯虚函数和抽象类
class Base
{
public:
//只要有一个纯虚函数,这个类称为抽象类
//特点;无法实例化对象
virtual void func() = 0;//注意:不要忘掉virtual!
//抽象类的子类必须要重写父类中的纯虚函数,否则也属于抽象类
};
class Son :public Base
{
public:
void func()
{
cout << "func函数调用" << endl;
}
};
void test()
{
//Base b1; 抽象类无法实例化对象
Son s1;//子类重写父类的虚函数,否则无法实例化对象
Base* abc = new Son;
abc->func();
}
int main(void)
{
test();
system("pause");
return 0;
}
奇牛
什么时候使用纯虚函数
某些类,在现实角度和项目实现角度,都不需要实例化(不需要创建它的对象),
这个类中定义的某些成员函数,只是为了提供一个形式上的接口,准备让子类来做具体的实现。
此时,这个方法,就可以定义为“纯虚函数”, 包含纯虚函数的类,就称为抽象类。
纯虚函数的使用方法
用法:纯虚函数,使用virtual和 =0
纯虚函数的注意事项:
父类声明某纯虚函数后,
那么它的子类,
- 要么实现这个纯虚函数 (最常见)
- 要么继续把这个纯虚函数声明为纯虚函数,这个子类也成为抽象类
要么不对这个纯虚函数做任何处理,等效于上一种情况(该方式不推荐
虚析构和纯虚析构
#include<iostream>
#include<string>
using namespace std;
//虚析构和纯虚析构
class Animal
{
public:
Animal()
{
cout << "Animal的构造函数调用" << endl;
}
~Animal()
{
cout << "Animal的析构造函数调用" << endl;
//纯虚函数,不需要实现
virtual void speak() = 0;
};
class Cat :public Animal
{
public:
Cat(string name)
{
m_Name = new string(name);
}
virtual void speak()
{
cout << "Cat的构造函数调用" << endl;
cout << *m_Name << "小猫在说话" << endl;
}
~Cat()
{
if (m_Name != NULL)
{
cout << "Cat的析构函数调用" << endl;
delete m_Name;
m_Name = NULL;
}
}
string* m_Name;
};
void test01()
{
Animal* animal = new Cat("Tom");
animal->speak();
/*
父类的指针在析构的时候,不会调用子类中的析构函数,
*/
delete animal;
}
int main(void)
{
test01();
system("pause");
return 0;
}
运行结果
(没有调用字类析构函数 )
多态使用的时候,如果子类中有属性开辟到堆区,那么父类指针在释放的时无法调用到子类的析构代码
解决方法:将父类中的析构函数改为虚析构或者纯虚析构
虚析构和纯析构共性:
可以解决父类指针释放子类对象,
都需要有具体的含函数实现
虚析构和纯虚构的区别:
如果是纯虚析构,该类属于抽象类,无法实例化对象
虚析构语法;
virtual ~类名(){}
纯虚析构语法:
virtual ~类名() = 0;//声明
类名::~类名(){}
#include<iostream>
#include<string>
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)
{
m_Name = new string(name);
}
virtual void speak()
{
cout << "Cat的构造函数调用" << endl;
cout << *m_Name << "小猫在说话" << endl;
}
~Cat()
{
if (m_Name != NULL)
{
cout << "Cat的析构函数调用" << endl;
delete m_Name;
m_Name = NULL;
}
}
string* m_Name;
};
void test01()
{
Animal* animal = new Cat("Tom");
animal->speak();
/*
父类的指针在析构的时候,不会调用子类中的析构函数,
导致子类如果有堆区属性,会出现内存的泄漏情况。
解决:将父类的析构函数改为虚析构
*/
delete animal;
}
int main(void)
{
test01();
system("pause");
return 0;
}
总结:
- 虚析构或纯虚析构就是用来解决通过父类指针释放子类对象问题
- 如果子类中没有堆区数据,可以不写为虚析构或纯虚析构
- 拥有纯虚析构函数的类也属于抽象类