类和对象
引言
C++语言作为一种面向对象编程(OOP)的强大工具,赋予开发者将现实世界中的概念映射到代码中的能力。而类与对象正是这门语言的基石,它们构成了复杂系统的基础单元。通过类的定义,我们能够抽象出具有共同特征和行为的模板,而对象则是类的具体实例。类与对象的引入不仅使程序更具逻辑性和可扩展性,还让代码更具复用性和可维护性。
在本文中,我们将深入探讨C++中的类与对象,了解如何定义类、创建对象、使用构造函数与析构函数,并探索类的继承、多态等高级特性。无论你是C++的新手还是经验丰富的开发者,希望本文能为你提供关于类与对象的清晰理解与实用指南。让我们开始吧!
目录
类的定义
1. 类定义的格式
- 下面的代码示例中:
class
为定义类的关键字,Stack
为类的名字,{}
中为类的主体,注意类定义结束时后面的分号不能省略。类体中内容称为类的成员:类中的变量称为类的属性或成员变量; 类中的函数称为类的方法或者成员函数。 定义在类里面的成员函数默认为inline也就是内联函数。
代码示例
#include<iostream>
using namespace std;
class Stack
{
public:
// 成员函数
void Init(int n = 4)
{
array = (int*)malloc(sizeof(int) * n);
if (nullptr == array)
{
perror("malloc申请空间失败");
return;
}
capacity = n;
top = 0;
}
void Push(int x)
{
// ...扩容
array[top++] = x;
}
int Top()
{
assert(top > 0);
return array[top - 1];
}
void Destroy()
{
free(array);
array = nullptr;
top = capacity = 0;
}
private:
// 成员变量
int* array;
size_t capacity;
size_t top;
}; // 分号不能省略
int main()
{
Stack st; //通过实例化Stack定义一个对象st
//
st.Init();
st.Push(1);
st.Push(2);
cout << st.Top() << endl;
st.Destroy();
return 0;
}
- 为了区分成员变量,一般会在成员变量的命名上加一个特殊标识,比如在成员变量前面或者后面加
_
或者 以m
开头,不过在C++中这个并不是强制的,只是一些惯例而已。
代码示例
class Date
{
public:
void Init(int year, int month, int day)
{
_year = year;
_month = month;
_day = day;
}
private:
// 为了区分成员变量,⼀般习惯上成员变量
// 会加⼀个特殊标识,如_ 或者 m开头
int _year; // year_ m_year
int _month;
int _day;
};
int main()
{
Date d;
d.Init(2024, 3, 31);
return 0;
}
- C++中
struct
也可以定义类,因为C++是兼容C中struct
的用法,同时在C++中struct
升级成了类,明显的变化是struct
中可以定义函数,一般情况下我们还是推荐用class
定义类。
代码示例
#include<iostream>
using namespace std;
// C++将struct升级成了类,其特点为:
// 1、类⾥⾯可以定义函数 2、struct名称就可以代表类型
// 同时C++兼容C中struct的⽤法
//C的用法
typedef struct ListNodeC
{
struct ListNodeC* next;
int val;
}LTNode;
//C++的用法
// 不再需要typedef,ListNodeCPP就可以代表类型
struct ListNodeCPP
{
void Init(int x)
{
next = nullptr;
val = x;
}
ListNodeCPP* next;
int val;
};
2. 访问限定符
- 访问限定符是C++的一种实现封装的方式,用类将对象的属性和方法结合在一起,让对象更加完善,通过访问权限,选择性的将其接口提供给外部的用户使用。
- 访问限定符一共分为三种,
public
修饰的成员在类外可以直接被访问;protected
和private
修饰的成员在类外不能直接被访问。protected
和private
的区别在后面的继承才能体现出来。 - 访问权限的作用域从该访问限定符出现的位置开始直到下一个访问限定符出现时结束,如果没有下一个访问限定符的出现,那么作用域在
}
结束即类结束。 - 使用
class
定义成员没有被访问限定符修饰时默认为private
,struct
默认为public
。 - 一般成员变量都会被限制为
private/protected
,需要给别人使用的成员函数会放为public
。
3. 类域
- 函数和变量的声明和定义分离,需要指定类域
- 类定义了一个新的作用域,类的所有成员都在类的作用域中,在类体外需要定义成员时,需要使用
::
作用域操作符指明成员属于哪个类域。 - 类域影响的是编译的查找规则,下面程序中
Init
如果不指定类域Stack
,那么编译器就把Init
当成全局函数,那么编译时,找不到array
等成员的声明/定义在哪里,就会报错。指定类域Stack
,就是知道Init
是成员函数,当前域找不到的array
等成员,就会到类域中去查找。
代码示例
#include<iostream>
using namespace std;
class Stack
{
public:
// 成员函数
void Init(int n = 4);
private:
// 成员变量
int* array;
size_t capacity;
size_t top;
};
// 声明和定义分离,需要指定类域
void Stack::Init(int n)
{
array = (int*)malloc(sizeof(int) * n);
if (nullptr == array)
{
perror("malloc申请空间失败");
return;
}
capacity = n;
top = 0;
}
int main()
{
Stack st;
st.Init();
return 0;
}
实例化
1. 实例化的概念
- 用类类型(自定义类型)在物理内存中创建对象的过程,称为类实例化出对象。
- 被实例化出的对象就有了这个类类型的成员变量和可以调用的成员函数。
- 类是对象进行的一种抽象描述,描述限定了类有哪些成员变量,这些成员变量只是声明,没有分配空间,用类实例化出对象时,才会分配空间。
- 一个类可以实例化出多个对象,实例化出的对象占用实际的物理空间,存储类成员变量。
2. 对象大小
-
类实例化出的每个对象都有独立的数据空间,包含成员变量,但不包含成员函数。 成员函数编译成汇编指令
[call 地址]
存储在代码段,对象中只需存储成员函数的指针。然而,由于同一类的不同对象共享相同的成员函数指针,存储在对象中会导致重复浪费。实际上,函数指针不需要存储在对象中,因为编译器在编译链接时已确定函数地址,只有在动态多态时才需要在运行时查找函数地址。 -
C++规定类实例化的对象也要符合内存对齐的规则,这个规则我在 程序开发中的编译链接中也介绍过,如果大家对此还有疑惑的话,可以先跳转复习一下。在这里我就简单贴一个内存对齐的规则了。
-
注:如果一个类没有成员变量,其对象大小也是1字节,为了占位表示对象存在。
This指针
- 成员函数通过隐含的this指针区分不同对象。编译器在编译时会在成员函数的形参列表的第一个位置中添加一个当前类类型的this指针,例如Init函数的实际原型为
void Init(Date* const this, int year, int month, int day)
。成员函数内部访问成员变量时,实际上是通过this指针访问的,例如this->_year = year
。 - C++规定不能在实参和形参的位置显示的写
this
指针(编译时编译器会处理),但是可以在函数体内显示使用this
指针。
类的默认成员函数
默认成员函数——用户没有显式实现,编译器会自动生成的成员函数。一个类中,我们不写的情况下编译器会默认生成以下6个默认成员函数,C++11以后还会增加两个默认成员函数——移动构造和移动赋值。
1. 构造函数
构造函数是特殊的成员函数,需要注意的是,构造函数虽然名称叫构造,但是构造函数的主要任务并不是开空间创建对象(我们常使用的局部对象是栈帧创建时,空间早就开好了),而是在对象实例化时初始化对象。构造函数的本质是要替代我们以前Stack
类中写的Init
函数的功能,构造函数自动调用的特点就完美的替代的了Init
函数。
构造函数的特点:
- 函数名与类名相同。
- 无返回值。 (不需要给返回值,也不需要写
void
) - 对象实例化时系统会自动调用对应的构造函数。
- 构造函数可以重载。
- 如果类中没有显式定义构造函数,则C++编译器会自动生成一个无参的默认构造函数,一旦用户显式定义编译器将不再生成。
- 无参构造函数、全缺省构造函数、我们不写构造时编译器默认生成的构造函数,都叫做默认构造函数(其实就是无实参调用的构造函数)。但是这三个函数有且只有一个存在,不能同时存在。无参构造函数和全缺省构造函数虽然构成函数重载,但是调用时会存在歧义。
- 我们不写,编译器默认生成的构造,对内置类型成员变量的初始化没有要求,也就是说是是否初始化是不确定的,看编译器。对于自定义类型成员变量,要求调用这个成员变量的默认构造函数初始化。如果这个成员变量,没有默认构造函数,那么就会报错。
说明:C++把类型分成内置类型(基本类型)和自定义类型。内置类型就是语言提供的原生数据类型,如:int/char/double/指针等,自定义类型就是我们使用class/struct等关键字自己定义的类型。
总结:大多数情况,构造函数需要我们自己去实现,少数情况类似MyQueue且Stack有默认构造时,MyQueue自动生成的就可以用。因此我们应该做到——应写尽写。
代码示例
#include<iostream>
using namespace std;
class Date
{
public:
// 1.⽆参构造函数
Date()
{
_year = 1;
_month = 1;
_day = 1;
}
// 2.带参构造函数
Date(int year, int month, int day)
{
_year = year;
_month = month;
_day = day;
}
// 3.全缺省构造函数
/*
Date(int year = 1, int month = 1, int day = 1)
{
_year = year;
_month = month;
_day = day;
}*/
void Print()
{
cout << _year << "/" << _month << "/" << _day << endl;
}
private:
int _year;
int _month;
int _day;
};
int main()
{
// 如果留下三个构造中的第⼆个带参构造,第⼀个和第三个注释掉
// 编译报错:error C2512: “Date”: 没有合适的默认构造函数可⽤
Date d1; // 调⽤默认构造函数
Date d2(2025, 1, 1); // 调⽤带参的构造函数
// 注意:如果通过⽆参构造函数创建对象时,对象后⾯不⽤跟括号,
//否则编译器⽆法区分这⾥是函数声明还是实例化对象
// warning C4930: “Date d3(void)”: 未调⽤原型函数(是否是有意⽤变量定义的?)
Date d3();
d1.Print();
d2.Print();
return 0;
}
/*
#include<iostream>
using namespace std;
typedef int STDataType;
class Stack
{
public:
Stack(int n = 4)
{
_a = (STDataType*)malloc(sizeof(STDataType) * n);
if (nullptr == _a)
{
perror("malloc申请空间失败");
return;
}
_capacity = n;
_top = 0;
}
// ...
private:
STDataType * _a;
size_t _capacity;
size_t _top;
};
// 两个Stack实现队列
class MyQueue
{
public:
//编译器默认⽣成MyQueue的构造函数调⽤了Stack的构造,完成了两个成员的初始化
private:
Stack pushst;
Stack popst;
};
int main()
{
MyQueue mq;
return 0;
}
*/
2.析构函数
析构函数与构造函数功能相反,析构函数不是完成对对象本身的销毁,比如局部对象是存在栈帧的,函数结束栈帧销毁,他就释放了,不需要我们管,C++规定对象在销毁时会自动调用析构函数,完成对象中资源的清理释放工作。析构函数的功能类比我们之前Stack实现的Destroy功能,而像Date没有Destroy,其实就是没有资源需要释放,所以严格说Date是不需要析构函数的。
析构函数的特点:
-
析构函数命名是在类名前加上字符 ~。
-
无参数无返回值。 (这里跟构造类似,也不需要加
void
) -
一个类只能有一个析构函数。若未显式定义,系统会自动生成默认的析构函数。
-
对象生命周期结束时,系统会自动调用析构函数。
-
跟构造函数类似,我们不写编译器自动生成的析构函数对内置类型成员不做处理,自定类型成员会调用他的析构函数(无论是否显式写)。
-
如果类中没有申请资源时,析构函数可以不写,直接使用编译器生成的默认析构函数,如
Date
;如果默认生成的析构就可以用,也就不需要显式写析构,如MyQueue
;但是有资源申请时,一定要自己写析构,否则会造成资源泄漏,如Stack
。 -
一个局部域的多个对象,C++规定后定义的先析构。
代码示例
对比一下用C++和C实现的Stack解决之前括号匹配问题isValid,我们发现有了构造函数和析构函数确实方便了很多
3.拷贝构造函数
如果一个构造函数的第一个参数是自身类类型的引用,且任何额外的参数都有缺省值,则此构造函数也叫做拷贝构造函数。拷贝构造的作用就是用一个对象拷贝初始化给另一个要创建的对象。
拷贝构造的特点:
- 拷贝构造函数是构造函数的一个重载。
- 拷贝构造函数的第一个参数必须是类类型对象的引用,使用传值方式编译器会直接报错,因为语法逻辑上会引发无穷递归调用。 拷贝构造函数也可以多个参数,但是第一个参数必须是类类型对象的引用,后面的参数必须有缺省值。
- C++规定自定义类型对象进行拷贝行为必须调用拷贝构造,所以这里自定义类型传值传参和传值返回都会调用拷贝构造完成。
- 若未显式定义拷贝构造,编译器会生成自动生成拷贝构造函数。自动生成的拷贝构造对内置类型成员变量会完成值拷贝/浅拷贝(一个字节一个字节的拷贝),对自定义类型成员变量会调用他的拷贝构造(深拷贝:更深一层次的拷贝,包括资源空间的拷贝,而不是使用同一块空间)。
-
像Date这样的类成员变量全是内置类型且没有指向什么资源,编译器自动生成的拷贝构造就可以完成需要的拷贝,所以不需要我们显式实现拷贝构造。像Stack这样的类,虽然也都是内置类型,但是_a指向了资源,编译器自动生成的拷贝构造完成的值拷贝/浅拷贝不符合我们的需求,所以需要我们自己实现深拷贝(对指向的资源也进行拷贝)。像MyQueue这样的类型内部主要是自定义类型Stack成员,编译器自动生成的拷贝构造会调用Stack的拷贝构造,也不需要我们显式实现MyQueue的拷贝构造。这里还有一个小技巧,如果一个类显式实现了析构并释放资源,那么他就需要显式写拷贝构造,否则就不需要。
-
传值返回会产生一个临时对象调用拷贝构造,传值引用返回,返回的是返回对象的别名(引用),没有产生拷贝。但是如果返回对象是一个当前函数局部域的局部对象,函数结束就销毁了,那么使用引用返回是有问题的,这时的引用相当于一个野引用,类似一个野指针一样。传引用返回可以减少拷贝,但是一定要确保返回对象,在当前函数结束后还在,才能用引用返回。
代码示例
#include<iostream>
using namespace std;
class Date
{
public:
Date(int year = 1, int month = 1, int day = 1)
{
_year = year;
_month = month;
_day = day;
}
// 编译报错:error C2652: “Date”: ⾮法的复制构造函数: 第⼀个参数不应是“Date”
//Date(Date d)
Date(const Date & d)
{
_year = d._year;
_month = d._month;
_day = d._day;
}
Date(Date* d)
{
_year = d->_year;
_month = d->_month;
_day = d->_day;
}
void Print()
{
cout << _year << "-" << _month << "-" << _day << endl;
}
private:
int _year;
int _month;
int _day;
};
void Func1(Date d)
{
cout << &d << endl;
d.Print();
}
// Date Func2()
Date& Func2()
{
Date tmp(2024, 7, 5);
tmp.Print();
return tmp;
}
int main()
{
Date d1(2024, 7, 5);
// C++规定⾃定义类型对象进⾏拷⻉⾏为必须调⽤拷⻉构造,所以这⾥传值传参要调⽤拷⻉
构造
// 所以这⾥的d1传值传参给d要调⽤拷⻉构造完成拷⻉,传引⽤传参可以较少这⾥的拷⻉
Func1(d1);
cout << &d1 << endl;
// 这⾥可以完成拷⻉,但是不是拷⻉构造,只是⼀个普通的构造
Date d2(&d1);
d1.Print();
d2.Print();
//这样写才是拷⻉构造,通过同类型的对象初始化构造,⽽不是指针
Date d3(d1);
d2.Print();
// 也可以这样写,这⾥也是拷⻉构造
Date d4 = d1;
d2.Print();
// Func2返回了⼀个局部对象tmp的引⽤作为返回值
// Func2函数结束,tmp对象就销毁了,相当于了⼀个野引⽤
Date ret = Func2();
ret.Print();
return 0;
}
#include<iostream>
using namespace std;
typedef int STDataType;
class Stack
{
public:
Stack(int n = 4)
{
_a = (STDataType*)malloc(sizeof(STDataType) * n);
if (nullptr == _a)
{
perror("malloc申请空间失败");
return;
}
_capacity = n;
_top = 0;
}
Stack(const Stack& st)
{
// 需要对_a指向资源创建同样⼤的资源再拷⻉值
_a = (STDataType*)malloc(sizeof(STDataType) * st._capacity);
if (nullptr == _a)
{
perror("malloc申请空间失败!!!");
return;
}
memcpy(_a, st._a, sizeof(STDataType) * st._top);
_top = st._top;
_capacity = st._capacity;
}
void Push(STDataType x)
{
if (_top == _capacity)
{
int newcapacity = _capacity * 2;
STDataType* tmp = (STDataType*)realloc(_a, newcapacity *
sizeof(STDataType));
if (tmp == NULL)
{
perror("realloc fail");
return;
}
_a = tmp;
_capacity = newcapacity;
}
_a[_top++] = x;
}
~Stack()
{
cout << "~Stack()" << endl;
free(_a);
_a = nullptr;
_top = _capacity = 0;
}
private:
STDataType* _a;
size_t _capacity;
size_t _top;
};
// 两个Stack实现队列
class MyQueue
{
public:
private:
Stack pushst;
Stack popst;
};
int main()
{
Stack st1;
st1.Push(1);
st1.Push(2);
// Stack不显⽰实现拷⻉构造,⽤⾃动⽣成的拷⻉构造完成浅拷⻉
// 会导致st1和st2⾥⾯的_a指针指向同⼀块资源,析构时会析构两次,程序崩溃
Stack st2 = st1;
MyQueue mq1;
// MyQueue⾃动⽣成的拷⻉构造,会⾃动调⽤Stack拷⻉构造完成pushst/popst
// 的拷⻉,只要Stack拷⻉构造⾃⼰实现了深拷⻉,他就没问题
MyQueue mq2 = mq1;
return 0;
}
4.赋值运算符重载
4.1运算符重载
- 当运算符被用于类类型的对象时,C++语言允许我们通过运算符重载的形式指定新的含义。C++规定类类型对象使用运算符时,必须转换成调用对应运算符重载,若没有对应的运算符重载,则会编译报错。
- 运算符重载是具有特殊名字的函数,他的名字是由
operator
和后面要定义的运算符共同构成。和其他函数⼀样,它也具有其返回类型和参数列表以及函数体。 - 重载运算符函数的参数个数和该运算符作用的运算对象数量一样多。一元运算符有一个参数,二元运算符有两个参数,二元运算符的左侧运算对象传给第一个参数,右侧运算对象传给第二个参数。
- 如果一个重载运算符函数是成员函数,则它的第一个运算对象默认传给隐式的
this
指针,因此运算符重载作为成员函数时,参数比运算对象少一个。 - 运算符重载以后,其优先级和结合性与对应的内置类型运算符保持⼀致。
- 不能通过连接语法中没有的符号来创建新的操作符:比如
operator@
。 .* :: sizeof ?: .
注意以上5个运算符不能重载。- 重载操作符至少有⼀个类类型参数,不能通过运算符重载改变内置类型对象的含义,如:
int operator+(int x, int y)
- 重载
++
运算符时,有前置++
和后置++
,运算符重载函数名都是operator++
,无法很好的区分。C++规定,后置++
重载时,增加⼀个int形参,跟前置++
构成函数重载,方便区分。 - 重载
<<
和>>
时,需要重载为全局函数,因为重载为成员函数,this
指针默认抢占了第⼀个形参位置,第⼀个形参位置是左侧运算对象,调用时就变成了对象<<cout
,不符合使用习惯和可读性。重载为全局函数把ostream/istream
放到第⼀个形参位置就可以了,第⼆个形参位置当类类型对象。
代码示例
#include<iostream>
using namespace std;
// 编译报错:“operator +”必须⾄少有⼀个类类型的形参
int operator+(int x, int y)
{
return x - y;
}
class A
{
public:
void func()
{
cout << "A::func()" << endl;
}
};
typedef void(A::*PF)(); //成员函数指针类型
int main()
{
// C++规定成员函数要加&才能取到函数指针
PF pf = &A::func;
A obj;//定义ob类对象temp
// 对象调⽤成员函数指针时,使⽤.*运算符
(obj.*pf)();
return 0;
}
#include<iostream>
using namespace std;
class Date
{
public:
Date(int year = 1, int month = 1, int day = 1)
{
_year = year;
_month = month;
_day = day;
}
void Print()
{
cout << _year << "-" << _month << "-" << _day << endl;
}
//private:
int _year;
int _month;
int _day;
};
// 重载为全局的⾯临对象访问私有成员变量的问题
// 有⼏种⽅法可以解决:
// 1、成员放公有
// 2、Date提供getxxx函数
// 3、友元函数
// 4、重载为成员函数
bool operator==(const Date& d1, const Date& d2)
{
return d1._year == d2._year
&& d1._month == d2._month
&& d1._day == d2._day;
}
int main()
{
Date d1(2024, 7, 5);
Date d2(2024, 7, 6);
// 运算符重载函数可以显⽰调⽤
operator==(d1, d2);
// 编译器会转换成 operator==(d1, d2);
d1 == d2;
return 0;
}
#include<iostream>
using namespace std;
class Date
{
public:
Date(int year = 1, int month = 1, int day = 1)
{
_year = year;
_month = month;
_day = day;
}
void Print()
{
cout << _year << "-" << _month << "-" << _day << endl;
}
bool operator==(const Date& d)
{
return _year == d._year
&& _month == d._month
&& _day == d._day;
}
Date& operator++()
{
cout << "前置++" << endl;
//...
return *this;
}
Date operator++(int)
{
Date tmp;
cout << "后置++" << endl;
//...
return tmp;
}
private:
int _year;
int _month;
int _day;
};
int main()
{
Date d1(2024, 7, 5);
Date d2(2024, 7, 6);
// 运算符重载函数可以显⽰调⽤
d1.operator==(d2);
// 编译器会转换成 d1.operator==(d2);
d1 == d2;
// 编译器会转换成 d1.operator++();
++d1;
// 编译器会转换成 d1.operator++(0);
d1++;
return 0;
}
4.2赋值运算符重载
赋值运算符重载是一个默认成员函数,用于完成两个已经存在的对象直接的拷贝赋值,这里要注意跟拷贝构造区分,拷贝构造用于一个对象拷贝初始化给另一个要创建的对象。
赋值运算符重载的特点:
-
赋值运算符重载是一个运算符重载,规定必须重载为成员函数。赋值运算重载的参数建议写成
const当前类类型引用
,否则会传值传参会有拷贝。 -
有返回值,且建议写成
当前类类型引用
,引用返回可以提⾼效率,有返回值目的是为了支持连续赋值场景。 -
没有显式实现时,编译器会自动生成⼀个默认赋值运算符重载,默认赋值运算符重载行为跟默认拷贝构造函数类似,对内置类型成员变量会完成值拷贝/浅拷贝(⼀个字节⼀个字节的拷贝),对自定义类型成员变量会调用他的赋值重载函数。
-
如果一个类显式实现了析构并释放资源,那么他就需要显式写赋值运算符重载,否则就不需要。
代码示例
class Date
{
public:
Date(int year = 1, int month = 1, int day = 1)
{
_year = year;
_month = month;
_day = day;
}
Date(const Date& d)
{
cout << " Date(const Date& d)" << endl;
_year = d._year;
_month = d._month;
_day = d._day;
}
// 传引⽤返回减少拷⻉
// d1 = d2;
Date& operator=(const Date& d)
{
// 不要检查自己给自己赋值的情况
if (this != &d)
{
_year = d._year;
_month = d._month;
_day = d._day;
}
// d1 = d2表达式的返回对象应该为d1,也就是*this
return *this;
}
void Print()
{
cout << _year << "-" << _month << "-" << _day << endl;
}
private:
int _year;
int _month;
int _day;
};
int main()
{
Date d1(2024, 7, 5);
Date d2(d1);
Date d3(2024, 7, 6);
d1 = d3;
// 需要注意这⾥是拷⻉构造,不是赋值重载
// 请牢牢记住赋值重载完成两个已经存在的对象直接的拷⻉赋值
// ⽽拷⻉构造⽤于⼀个对象拷⻉初始化给另⼀个要创建的对象
Date d4 = d1;
return 0;
}
5.取地址运算符重载
5.1 const成员函数
- 将
const
修饰的成员函数称之为const
成员函数,const
修饰成员函数放到成员函数参数列表的后
面。 const
实际修饰该成员函数隐含的this
指针,表明在该成员函数中不能对类的任何成员进行修改。
const
修饰Date
类的Print
成员函数,Print
隐含的this
指针由Date* const this
变为const Date* const this
代码示例
#include<iostream>
using namespace std;
class Date
{
public:
Date(int year = 1, int month = 1, int day = 1)
{
_year = year;
_month = month;
_day = day;
}
// void Print(const Date* const this) const
void Print() const
{
cout << _year << "-" << _month << "-" << _day << endl;
}
private:
int _year;
int _month;
int _day;
};
int main()
{
// 这⾥⾮const对象也可以调⽤const成员函数是⼀种权限的缩⼩
Date d1(2024, 7, 5);
d1.Print();
const Date d2(2024, 8, 5);
d2.Print();
return 0;
}
5.2 取地址运算符重载
取地址运算符重载分为普通取地址运算符重载和const取地址运算符重载,一般这两个函数编译器自动
生成的就可以够我们用了,不需要去显式实现。
代码示例
class Date
{
public:
Date* operator&()
{
return this;
// return nullptr;
}
const Date * operator&()const
{
return this;
// return nullptr;
}
private:
int _year; // 年
int _month; // ⽉
int _day; // ⽇
};
构造函数的初始化列表
- 构造函数初始化不仅可以使用使用函数体内赋值,还可以使用初始化列表,初始化列表的使用方式是以一个冒号开始,接着是一个以逗号分隔的数据成员列表,每个"成员变量"后面跟一个放在括号中的初始值或表达式。
- 每个成员变量在初始化列表中只能出现一次,语法理解上初始化列表可以认为是每个成员变量定义初始化的地方。
- C++11支持在成员变量声明的位置给缺省值,这个缺省值主要是给没有显式在初始化列表初始化的成员使用的。
- 初始化列表中按照成员变量在类中声明顺序进行初始化,跟成员在初始化列表出现的的先后顺序无关。建议声明顺序和初始化列表顺序保持⼀致。
代码示例:初始化列表使用方式
#include<iostream>
using namespace std;
class Time
{
public:
Time(int hour)
:_hour(hour)
{
cout << "Time()" << endl;
}
private:
int _hour;
};
class Date
{
public:
//初始化列表
Date(int& x, int year = 1, int month = 1, int day = 1)
:_year(year)
, _month(month)
, _day(day)
, _t(12)
, _ref(x)
, _n(1)
{
// error C2512: “Time”: 没有合适的默认构造函数可⽤
// error C2530 : “Date::_ref” : 必须初始化引⽤
// error C2789 : “Date::_n” : 必须初始化常量限定类型的对象
}
void Print() const
{
cout << _year << "-" << _month << "-" << _day << endl;
}
private://成员变量声明的地方
int _year = 1; //缺省值
int _month;
int _day;
Time _t; // 没有默认构造
int& _ref; // 引⽤
const int _n; // const
};
int main()
{
int i = 0;
Date d1(i);
d1.Print();
return 0;
}
编译器判定成员变量初始化的顺序
类型转换
- C++支持
内置类型
隐式类型转换为类类型对象
,需要有相关内置类型为参数的构造函数 - 如构造函数前面加
explicit
就不再支持隐式类型转换
代码示例
#include<iostream>
using namespace std;
class A
{
public:
// 构造函数explicit就不再⽀持隐式类型转换
// explicit A(int a1)
A(int a1)
:_a1(a1)
{}
//explicit A(int a1, int a2)
A(int a1, int a2)
:_a1(a1)
, _a2(a2)
{}
void Print()
{
cout << _a1 << " " << _a2 << endl;
}
private:
int _a1 = 1;
int _a2 = 2;
};
int main()
{
// 1构造⼀个A的临时对象,再⽤这个临时对象拷⻉构造aa3
// 编译器遇到连续构造+拷⻉构造->优化为直接构造
A aa1 = 1;
aa1.Print();
const A& aa2 = 1;
// C++11之后才⽀持多参数转化
A aa3 = { 2,2 };
return 0;
}
static成员
- 用static修饰的成员变量,称之为静态成员变量,静态成员变量一定要在类外进行初始化,初始化时需注意指明类域。
- 静态成员变量为所有类对象所共享,不属于某个具体的对象,不存在对象中,存放在静态区。
- 用static修饰的成员函数,称之为静态成员函数,静态成员函数没有this指针。
- 静态成员函数中可以访问其他的静态成员,但是不能访问非静态的,因为没有this指针。
- 非静态的成员函数,可以访问任意的静态成员变量和静态成员函数。
- 突破类域就可以访问静态成员,可以通过
类名::静态成员
或者对象.静态成员
来访问静态成员变量
和静态成员函数。 - 静态成员也是类的成员,受
public、protected、private
访问限定符的限制。 - 静态成员变量不能在声明位置给缺省值初始化,因为缺省值是个构造函数初始化列表的,静态成员
变量不属于某个对象,不走构造函数初始化列表。
代码示例
#include<iostream>
using namespace std;
class A
{
public:
A()
{
++_scount;
}
A(const A& t)
{
++_scount;
}
~A()
{
--_scount;
}
static int GetACount()
{
return _scount;
}
private:
// 类⾥⾯声明
static int _scount;
};
// 类外⾯初始化
int A::_scount = 0;
int main()
{
cout << A::GetACount() << endl;
A a1, a2;
A a3(a1);
cout << A::GetACount() << endl;
cout << a1.GetACount() << endl;
// 编译报错:error C2248: “A::_scount”: ⽆法访问 private 成员(在“A”类中声明)
//cout << A::_scount << endl;
return 0;
}
友元
- 友元提供了⼀种突破类访问限定符封装的方式,友元分为:友元函数和友元类,在函数声明或者类
声明的前面加friend
,并且把友元声明放到一个类的里面。 - 外部友元函数可访问类的私有和保护成员,友元函数仅仅是一种声明,他不是类的成员函数。
- 友元函数可以在类定义的任何地方声明,不受类访问限定符限制。
- 一个函数可以是多个类的友元函数。
- 友元类中的成员函数都可以是另一个类的友元函数,都可以访问另一个类中的私有和保护成员。
- 友元类的关系是单向的,不具有交换性,比如A类是B类的友元,但是B类不是A类的友元。
- 友元类关系不能传递,如果A是B的友元, B是C的友元,但是A不是B的友元。
- 友元会增加耦合度,破坏封装,因此友元不宜多用。
代码示例
#include<iostream>
using namespace std;
// 前置声明,都则A的友元函数声明编译器不认识B
class B;
class A
{
// 友元声明
friend void func(const A& aa, const B& bb);
private:
int _a1 = 1;
int _a2 = 2;
};
class B
{
// 友元声明
friend void func(const A& aa, const B& bb);
private:
int _b1 = 3;
int _b2 = 4;
};
void func(const A& aa, const B& bb)
{
cout << aa._a1 << endl;
cout << bb._b1 << endl;
}
int main()
{
A aa;
B bb;
func(aa, bb);
return 0;
}
内部类
- 如果一个类定义在另⼀个类的内部,这个内部类就叫做内部类。内部类是一个独立的类,跟定义在
全局相比,他只是受外部类类域限制和访问限定符限制,所以外部类定义的对象中不包含内部类。 - 内部类默认是外部类的友元类。
- 内部类本质也是一种封装,当A类跟B类紧密关联,A类实现出来主要就是给B类使用,那么可以考
虑把A类设计为B的内部类,如果放到private/protected位置,那么A类就是B类的专属内部类,其
他地方都不可使用。
匿名对象
- 用
类型(实参)
定义出来的对象叫做匿名对象,相比之前我们定义的类型 对象名(实参)
定义出来的
叫有名对象。 - 匿名对象生命周期只在当前一行,一般临时定义一个对象当前用一下即可,就可以定义匿名对象。
对象拷贝时编译器优化
- 现代编译器会为了尽可能提高程序的效率,在不影响正确性的情况下会尽可能减少一些传参和传参
过程中可以省略的拷贝。 - 如何优化C++标准并没有严格规定,各个编译器会根据情况自行处理。当前主流的相对新⼀点的编
译器对于连续⼀个表达式步骤中的连续拷贝会进行合并优化,有些更新更"激进"的编译还会进行跨
行跨表达式的合并优化。
习题——日期类实现
Date.h
文件
#pragma once
#include<iostream>
using namespace std;
#include<assert.h>
class Date
{
// 友元函数声明
friend ostream& operator<<(ostream& out, const Date& d);
friend istream& operator>>(istream& in, Date& d);
public:
Date(int year = 1900, int month = 1, int day = 1);
void Print() const;
// 直接定义类⾥⾯,他默认是inline
// 频繁调⽤
int GetMonthDay(int year, int month)
{
assert(month > 0 && month < 13);
static int monthDayArray[13] = { -1, 31, 28, 31, 30, 31, 30,31, 31, 30, 31, 30, 31 };
// 365天 5h +
if (month == 2 && (year % 4 == 0 && year % 100 != 0) || (year% 400 == 0))
{
return 29;
}
else
{
return monthDayArray[month];
}
}
bool CheckDate();
bool operator<(const Date& d) const;
bool operator<=(const Date& d) const;
bool operator>(const Date& d) const;
bool operator>=(const Date& d) const;
bool operator==(const Date& d) const;
bool operator!=(const Date& d) const;
// d1 += 天数
Date& operator+=(int day);
Date operator+(int day) const;
// d1 -= 天数
Date& operator-=(int day);
Date operator-(int day) const;
// d1 - d2
int operator-(const Date& d) const;
// ++d1 -> d1.operator++()
Date& operator++();
// d1++ -> d1.operator++(0)
// 为了区分,构成重载,给后置++,强⾏增加了⼀个int形参
// 这⾥不需要写形参名,因为接收值是多少不重要,也不需要⽤
// 这个参数仅仅是为了跟前置++构成重载区分
Date operator++(int);
Date& operator--();
Date operator--(int);
// 流插⼊
// 不建议,因为Date* this占据了⼀个参数位置,使⽤d<<cout不符合习惯
//void operator<<(ostream& out);
private:
int _year;
int _month;
int _day;
};
// 重载
ostream& operator<<(ostream& out, const Date& d);
istream& operator>>(istream& in, Date& d);
Date.cpp文件
#include"Date.h"
bool Date::CheckDate()
{
if (_month < 1 || _month > 12|| _day < 1 || _day > GetMonthDay(_year, _month))
{
return false;
}
else
{
return true;
}
}
Date::Date(int year, int month, int day)
{
_year = year;
_month = month;
_day = day;
if (!CheckDate())
{
cout << "⽇期⾮法" << endl;
}
}
void Date::Print() const
{
cout << _year << "-" << _month << "-" << _day << endl;
}
// d1 < d2
bool Date::operator<(const Date& d) const
{
if (_year < d._year)
{
return true;
}
else if (_year == d._year)
{
if (_month < d._month)
{
return true;
}
else if (_month == d._month)
{
return _day < d._day;
}
}
return false;
}
// d1 <= d2
bool Date::operator<=(const Date& d) const
{
return *this < d || *this == d;
}
bool Date::operator>(const Date& d) const
{
return !(*this <= d);
}
bool Date::operator>=(const Date& d) const
{
return !(*this < d);
}
bool Date::operator==(const Date& d) const
{
return _year == d._year
&& _month == d._month
&& _day == d._day;
}
bool Date::operator!=(const Date& d) const
{
return !(*this == d);
}
// d1 += 50
// d1 += -50
Date& Date::operator+=(int day)
{
if (day < 0)
{
return *this -= -day;
}
_day += day;
while (_day > GetMonthDay(_year, _month))
{
_day -= GetMonthDay(_year, _month);
++_month;
if (_month == 13)
{
++_year;
_month = 1;
}
}
return *this;
}
Date Date::operator+(int day) const
{
Date tmp = *this;
tmp += day;
return tmp;
}
// d1 -= 100
Date& Date::operator-=(int day)
{
if (day < 0)
{
return *this += -day;
}
_day -= day;
while (_day <= 0)
{
--_month;
if (_month == 0)
{
_month = 12;
_year--;
}
// 借上⼀个⽉的天数
_day += GetMonthDay(_year, _month);
}
return *this;
}
Date Date::operator-(int day) const
{
Date tmp = *this;
tmp -= day;
return tmp;
}
//++d1
Date& Date::operator++()
{
*this += 1;
return *this;
}
// d1++
Date Date::operator++(int)
{
Date tmp(*this);
*this += 1;
return tmp;
}
Date& Date::operator--()
{
*this -= 1;
return *this;
}
Date Date::operator--(int)
{
Date tmp = *this;
*this -= 1;
return tmp;
}
// d1 - d2
int Date::operator-(const Date& d) const
{
Date max = *this;
Date min = d;
int flag = 1;
if (*this < d)
{
max = d;
min = *this;
flag = -1;
}
int n = 0;
while (min != max)
{
++min;
++n;
}
return n * flag;
}
ostream& operator<<(ostream& out, const Date& d)
{
out << d._year << "年" << d._month << "⽉" << d._day << "⽇" << endl;
return out;
}
istream& operator>>(istream& in, Date& d)
{
cout << "请依次输⼊年⽉⽇:>";
cin >> d._year >> d._month >> d._day;
if (!d.CheckDate())
{
cout << "⽇期⾮法" << endl;
}
return in;
}
test.cpp文件
#include"Date.h"
void TestDate1()
{
// 这⾥需要测试⼀下⼤的数据+和-
Date d1(2024, 4, 14);
Date d2 = d1 + 30000;
d1.Print();
d2.Print();
Date d3(2024, 4, 14);
Date d4 = d3 - 5000;
d3.Print();
d4.Print();
Date d5(2024, 4, 14);
d5 += -5000;
d5.Print();
}
void TestDate2()
{
Date d1(2024, 4, 14);
Date d2 = ++d1;
d1.Print();
d2.Print();
Date d3 = d1++;
d1.Print();
d3.Print();
/*d1.operator++(1);
d1.operator++(100);
d1.operator++(0);
d1.Print();*/
}
void TestDate3()
{
Date d1(2024, 4, 14);
Date d2(2034, 4, 14);
int n = d1 - d2;
cout << n << endl;
n = d2 - d1;
}
void TestDate4()
{
Date d1(2024, 4, 14);
Date d2 = d1 + 30000;
// operator<<(cout, d1)
cout << d1;
cout << d2;
cin >> d1 >> d2;
cout << d1 << d2;
}
void TestDate5()
{
const Date d1(2024, 4, 14);
d1.Print();
//d1 += 100;
d1 + 100;
Date d2(2024, 4, 25);
d2.Print();
d2 += 100;
d1 < d2;
d2 < d1;
}
int main()
{
return 0;
}