作者:王昊成(小红书:秋来拾光),无所不能哈基咪
本文由同学分享个人经验,仅供学习交流,严禁倒卖。 具体要求请以学校及学院最新发布的信息为准。
类与对象
类与对象
面向对象程序设计的特点
封装性
• 将同类事物的共同属性封装为一类
继承性
• 从其它事物中继承某些属性
多态性
• 函数、运算符重载
• 虚函数
类的主要组成
• 类的成员变量
• 类的成员函数
类的确定
• 抽象事物的共同特征做为类的成员(以变量形式描述)
• 将对事物共同特征的处理设计为成员函数
类的定义
理解为定义一种新的数据类型
class <自定义类类型名> {
private:
<各私有成员说明>;
public:
<各公有成员说明>;
protected:
<各保护成员说明>;
<以关键字friend开头的友元说明>;
};//注意类定义后面带分号
类名
• 标识符,表示类的名称,理解为新的数据类型名,可以像int等数据类型一样说明变量(即类对象)
成员
• 按功能划分
– 成员变量
– 成员函数
• 按访问权限划分
– 公有成员(由public标识)
– 私有成员(由private标识,为默认权限) 在类中,不做特殊说明,所指的成员函数为私有类型。
– 保护成员(由protected标识)
成员变量
• 类的数据成员
• 代表该类对象含有的数据(描述属性)
• 包括普通变量、数组、指针、结构、类对象等
成员函数
• 即函数成员,对该类对象所含数据进行操作的方法
• 既可放于类定义的花括号之中,也可按类外定义方式放于之外(但要求类体内必须有其函数原型,且类定义外函数说明的前面必须用“<类名>::”来限定)
<返回值类型> <类名>::<函数名>(<参数表>) {<函数体>}
• 凡在类体中定义的函数成员均隐含为内联函数
私有成员
• 以关键字private说明
• 成员不能从外部进行访问
– 所谓类的外部是指类的定义之外以及类的成员函数定义之外
公有成员
• 以关键字public说明
• 成员能从外部进行访问
保护成员
• 以关键字protected说明
友元
• 以关键字friend说明
• 不是本类的成员,但可以访问本类的私有成员
• private、public、protected以及friend“说明段”的顺序可以任意
每种说明符(private、public、protected,亦称访问限定符)可在类体中使用多次。或者一次也不出现。
访问限定符的作用域是从该说明符出现开始到下一个说明符之前或类体结束之前结束。
如果在类体起始点无访问说明符,系统默认定义为私有(private)。
访问限定符private(私有的)和protected(保护的)体现了类具有封装性(Encapsulation)
分文件保护(对分文件编写的一个案例,辅助大家大作业完成,考试不会考的)
头文件point.h 只删去函数功能
#pragma once//英 /ˈpræɡmə/
#include<iostream>
using namespace std;
class point {
public:
void setx(int x);
int getx();
void sety(int y);
int gety();
private:
int m_x;
int m_y;
};
头文件circle.h
#pragma once
#include<iostream>
using namespace std;
#include"point.h"
class circle{
public:
void setr(int r);
int getr();
void setcenter(point center);
point getcenter();
private:
int m_r;
point m_center;//另一个类对象作为成员变量
};
源文件
#include<iostream>
#include<string>
using namespace std;
#include"point.h"
#include"circle.h"
void isincircle(circle& c, point& p)
{
int x = p.getx() - c.getcenter().getx();
int y = p.gety() - c.getcenter().gety();
if (x * x + y * y < c.getr() * c.getr())
{
cout << "点在圆内" << endl;
}
else if (x * x + y * y == c.getr() * c.getr())
{
cout << "点在圆上" << endl;
}
else
{
cout << "点在圆外" << endl;
}
}
int main()
{
circle c;
c.setr(10);
point center;
center.setx(10);
center.sety(0);
c.setcenter(center);//创建圆
point p;
p.setx(10);
p.sety(10);//创建点
isincircle(c, p);//判断点和圆的位置关系
}
原文件point.cpp 只保留函数及对应功能
#include"point.h"
void point::setx(int x)
{
m_x = x;
}
int point::getx()
{
return m_x;
}//设置x坐标和获取x坐标
void point::sety(int y)
{
m_y = y;
}
int point::gety()
{
return m_y;
}//设置y坐标和获取y坐标
原文件circle.cpp
#include"circle.h"
void circle::setr(int r)
{
m_r = r;
}
int circle::getr()
{
return m_r;
}//设置半径和获取半径
void circle::setcenter(point center)
{
m_center = center;
}
point circle::getcenter()
{
return m_center;
}//设置圆心和获取圆心
this指针
当类成员函数调用中参数包括类的对象时不用this可以识别成员数据的归属吗?
参数类与这个类有同名成员变量
成员函数中,直接写的成员名默认属于当前调用该函数的对象(即隐式的this指向的对象);通过参数对象名。成员名访问的,属于传入的参数对象。二者作用域清晰,编译器不会混淆,无需显式写this也能正确识别归属。
#include <iostream>
using namespace std;
class Student {
public:
int score; // 成员变量
// 成员函数:参数是另一个 Student 对象
void compare(Student other) {
// 直接写 score → 属于【当前调用这个函数的对象】
cout << "我的分数:" << score << endl;
// other.score → 属于【传进来的那个对象】
cout << "对方分数:" << other.score << endl;
}
};
int main() {
Student A; A.score = 90;
Student B; B.score = 80;
// A 调用函数,B 当参数传进去
A.compare(B);
}
为什么要用 this 指针返回当前对象的指针(或引用)
为了实现「链式调用」,让代码更简洁、高效,同时避免不必要的对象拷贝。
常用的是返回this(当前对象的引用)
它始终指向当前正在调用该成员函数的那个对象本身
一、核心目的 1:实现链式调用(最常用)
如果不返回当前对象,每次调用成员函数都要写一行代码;返回this后,可 “连续调用” 多个成员函数,代码更简洁。
反例:不返回当前对象(代码冗余)
#include <iostream>
#include <string>
using namespace std;
class Student {
private:
string name;
int age;
public:// 无返回值:调用后无法继续链式操作
void setName(string name) {
this->name = name;
}
void setAge(int age) {
this->age = age;
}
void showInfo() {
cout << "姓名:" << name << ",年龄:" << age << endl;
}
};
int main() {
Student stu;// 必须逐行调用,无法链式
stu.setName("张三");
stu.setAge(20);
stu.showInfo();
return 0;
}
正例:返回*this(链式调用)
class Student {
private:
string name;
int age;
public:// 返回当前对象的引用(Student&)
Student& setName(string name) {
this->name = name;
return *this; // this是对象指针,*this是对象本身,返回引用
}
Student& setAge(int age) {
this->age = age;
return *this;
}
void showInfo() {
cout << "姓名:" << name << ",年龄:" << age << endl;
}
};
int main() {
Student stu;// 链式调用:一行完成多个操作
stu.setName("张三").setAge(20).showInfo();
return 0;
}
每次调用setName/setAge后,返回的是stu对象本身的引用(不是拷贝);因此后续的.setAge()/.showInfo()依然是对stu对象的操作,实现 “链式”。
Return 返回
分两种返回:值返回 / 引用返回
① 普通值返回 Student func(){ return *this; }
会重新拷贝一份新对象返回,不是原对象本身。
② 引用返回 Student& func(){ return *this; }
不拷贝、不新建、不重新赋值,直接把原对象本身起个别名传出去。
二.解决成员变量与局部变量的命名冲突
class pixel {
int x, y;
public:
pixel(int x, int y) {
this->x = x; // this->x 是成员变量,x 是参数
this->y = y;
}
};
template<class keytype>keytype Queue<keytype>::Delete(void) {
if (isEmpty()) {
cout << "the queue is empty" << endl;
}
else {
return queue[++front];
}
}
不管是普通类还是模板类,类的非静态成员函数(如isFull/isEmpty/Add)都遵循一个核心规则:
编译器会为每个非静态成员函数隐式添加一个this指针参数,
这个this指针就是当前调用该函数的对象地址,成员函数通过this指针访问当前对象的成员(变量 / 函数)。
空指针调用成员函数
#include<iostream>
using namespace std;
class person {
public:
void showclassname()
{
cout << "person" << endl;
}
void showpersonage()
{
if (this == NULL)
{
return;
}
cout << "age= " << m_age << endl;
//此处的m_age其实是this->m_age,由于没有定义(空)而错误
}
int m_age;
};
void test01()
{
person* p = NULL;//定义空指针,没有创建对象
p->showclassname();
p->showpersonage();
}
int main()
{
test01();
}
指向成员的指针
说明格式:<类型名> <类名>::<指针变量名>;
<类型名> (<类名>::<函数指针名>)(形参表);
对于已创建的对象,可将其包含的类成员(包括非静态成员变量和成员函数)地址赋给指向成员的指针
.* :对象 + 成员指针 配对使用 objx.pmi = 10; (objx.pmf)(5);直接相当于解引用了
->:对象指针 + 成员指针 配对使用
class X
{
public:
void f(int);
int a;
};
void X::f(int x)
{
a = x;
}
void main()
{
int X:: pmi = &X::a;
void (X:: * pmf)(int) = &X::f;
X objx;
objx.*pmi = 10;
cout << objx.a << endl;
(objx.*pmf)(5);
cout << objx.a << endl;
}
成员变量的可读性与可写性
核心就是通过封装成员函数来精准控制数据的读写权限—— 把数据藏在private里,外部不能直接碰,只能通过你提供的成员函数 “间接操作”,从而实现 “想让读就给读接口,想让写就给写接口,想限制写就加校验,想只读就不给写接口”。
读接口:int getNum() const {
return num;
}
函数末尾的const,本质是告诉编译器:这个成员函数是「只读函数」,执行过程中不会修改当前对象(this指针指向的对象)的任何非静态成员变量。
写接口:Cube& setlen(const int&len) {
m_len = len;
return *this;
}
1.只读权限 → 只提供「读接口(getter)」
class Test {
private:
int num = 10; // 私有数据
public:
// 仅提供读接口,无写接口
int getNum() const {
return num;
}
};
// 外部只能读,不能改
Test t;
cout << t.getNum(); // 合法(读)
// t.num = 20; // 报错(直接改私有数据)
// t.setNum(20); // 报错(无写接口)
2.可写权限 → 提供「写接口(setter)」,可加校验
class Test {
private:
int age = 20;
public:
// 写接口加校验,限制合法值
void setAge(int a) {
if (a >= 0 && a <= 120) {
age = a;
}
}
};
// 外部只能通过写接口修改,且只能改合法值
Test t;
t.setAge(25); // 合法
t.setAge(-5); // 无效(被校验拦截)
3.可读写权限 → 同时提供 getter + setter
class Test {
private:
string name = "张三";
public:
// 读接口
string getName() const { return name; }
// 写接口
void setName(string n) { name = n; }
};
// 外部可读可写,但必须通过接口
Test t;
cout << t.getName(); // 读
t.setName("李四"); // 写
为什么必须用成员函数,而不是直接暴露 public?
如果直接把数据设为public,相当于把 “钥匙” 直接给出去,完全失控:
写接口为什么传入的const的引用,不能直接传入原变量吗?
const 引用传参更高效、更安全—— 直接传原变量(值传递)是合法的,但会有额外开销
// 写法1:值传递(直接传原变量)
void setName(string newName) { // 无const&,直接传string类型
name = newName;
}
// 调用时传原变量/字面常量不可以
string myName = "张三";
p.setName(myName); // 传原变量(合法)
p.setName("李四"); // 传字面常量(不合法)
这种写法能运行,但核心问题是:值传递会触发 string 的拷贝构造函数,生成临时副本——string 是复杂类型(内部存字符数组)
优势 1:避免拷贝,提升效率
引用(&)的本质是 “变量的别名”,传引用时不会创建新的 string 对象,直接复用传入的变量 / 临时值;对比值传递:值传递:setName(myName) → 先拷贝myName生成newName(开销大)→ 再把newName赋值给name;引用传递:setName(const string& newName) → 无拷贝,直接把newName(myName 的别名)赋值给name(开销几乎为 0)。
优势 2:加const保证安全,兼容字面常量
不加const的引用(string& newName):无法接收字面常量(比如setName("李四")会编译报错,因为字面常量是右值,不能绑定到非 const 引用);加const的引用(const string& newName):既可以接收原变量(左值),也可以接收字面常量(右值),兼容性拉满;同时const承诺:函数内不会修改传入的newName,避免误操作传入的原变量(比如不小心写newName = "错误值",编译器会报错)。
构造函数+列表初始化
动态变量初始化本质上是调用的构造函数
Poker poker = new Poker(10, "club");
构造函数的规则
1.创建一个类,C++编译器会给每个类都添加至少三个函数:
默认构造(空实现) 析构函数(空实现) 拷贝构造(值拷贝)
2.如果我们写了有参构造函数,编译器就不再提供默认构造,依然提供拷贝构造
如果写了拷贝构造函数,编译器就不再提供其他的普通构造
默认构造函数:(不会赋值0,而是垃圾值和野指针)
Rectangle() {}
Rectangle() = default;
列表初始化格式:
class 类名 {
public:
// 列表初始化构造函数格式
类名(参数表) : 成员1(值1), 成员2(值2), ... {
函数体;
}
};
class Student {
public:
// 带参构造(用初始化列表初始化成员)
Student(string n, int a) : name(n), age(a) {
cout << "带参构造被调用" << endl;
}
private:
string name;
int age;
};
为什么要用初始化列表赋值?
const常量成员
const修饰的变量是只读的,只能在定义时赋值,一旦创建就无法修改,函数体里的赋值会直接编译报错
class Test {
private:
const int num; // 常量成员,只读
public:
// 正确:初始化列表在定义时赋值
Test(int n) : num(n) {}
// 错误:函数体是创建后赋值,const变量不允许修改
// Test(int n) { num = n; }
};
引用成员变量
C++ 的引用(&)必须在定义时绑定一个对象,不能先创建空引用,再后期绑定 —— 函数体里的赋值本质是给引用绑定的对象改值,而非绑定引用,直接编译报错。
class Test {
private:
int& ref; // 引用成员
public:
// 正确:初始化列表定义时绑定外部变量
Test(int& r) : ref(r) {}
// 错误:引用未定义就使用,无法后期绑定
// Test(int& r) { ref = r; }
};
复制过程都在函数体前面完成了,这函数体有啥用?
初始化列表只是 “初始化成员”,但构造函数的函数体可以做这些事:
执行额外的业务逻辑:如打印对象创建信息初始化动态资源
class Array {
private:
int arr; // 动态数组
int size;
public:
Array(int s) : size(s) { // 初始化列表处理size
// 函数体:分配堆内存(动态资源)
arr = new int[size];
// 函数体:初始化数组元素
for (int i=0; i<size; i++) {
arr[i] = 0;
}
}
};
处理复杂的初始化逻辑初始化列表只能做 “简单的成员赋值”,如果需要条件判断、循环等复杂逻辑,必须放在函数体中:
Student(string n, int a) : name(n) {
// 函数体:根据条件调整age
if (a < 0) {
age = 0;
cout << "年龄不合法,已设为0" << endl;
}
else {
age = a;
}
}
构造函数实例:
#include <iostream>
#include <string>
using namespace std;
class Person {
private:
string name;
int age;
string gender;
public:
// 重载1:无参构造(默认构造)——创建“默认对象”
Person() {
name = "未知";
age = 0;
gender = "未知";
cout << "无参构造:创建默认Person对象" << endl;
}
// 重载2:单参构造——只指定姓名,年龄/性别用默认值
Person(string n) {
name = n;
age = 0;
gender = "未知";
cout << "单参构造:创建姓名为" << n << "的Person对象" << endl;
}
// 重载3:三参构造——指定所有属性,精准创建对象
Person(string n, int a, string g) {
name = n;
age = a;
gender = g;
cout << "三参构造:创建完整属性的Person对象" << endl;
}
void showInfo() const {
cout << "姓名:" << name << ",年龄:" << age << ",性别:" << gender << endl;
}
};
int main() {
// 不同参数列表,调用不同的构造函数(重载生效)
Person p1; // 调用无参构造
Person p2("张三"); // 调用单参构造
Person p3("李四", 25, "男"); // 调用三参构造
p1.showInfo(); // 姓名:未知,年龄:0,性别:未知
p2.showInfo(); // 姓名:张三,年龄:0,性别:未知
p3.showInfo(); // 姓名:李四,年龄:25,性别:男
return 0;
}
拷贝构造函数
基本数据类型:数字(int/float)、字符串(string)、布尔值(bool)、null/undefined 等
特点:值直接存在栈内存中,拷贝时直接复制「具体的值」,不存在深浅之分。
引用数据类型:对象(Object)、数组(Array)、函数(Function)等
特点:实际数据存在堆内存,栈内存中只存一个「地址指针」,指向堆内存的真实数据。
关键:拷贝引用类型时,浅拷贝复制的是地址,深拷贝复制的是堆内存里的真实数据。
拷贝构造函数的唯一作用就是「创建新对象」,而「把一个已创建的对象复制给另一个已创建的对象」是赋值运算符重载的工作,不是拷贝构造函数。
#include<iostream>
using namespace std;
//1.构造函数的分类及调用
//分类:按照参数分为:无参构造函数 和 有参构造函数
//按照类型分为:普通构造函数 和 拷贝构造函数
class person
{
public:
int age;
person()
{
cout << "person的无参(默认)构造函数被调用了!" << endl;
}
person(int a)
{
age = a;
cout << "person的有参构造函数被调用了!" << endl;
}
//拷贝构造函数
person(const person &p)//限定本体不能改动
{
cout << "person的拷贝构造函数被调用了!" << endl;
age = p.age;//将传入的人身上所有属性拷贝过来
}
~person()
{
cout << "person的析构函数被调用了!" << endl;
}
};
//调用
void test01()
{
//1.括号法
person p;//默认(无参)构造函数的调用. 不要加括号,否则会被当成函数声明,不会认为在创建对象
person p2(10);//有参构造函数的调用
person p3(p2);//拷贝构造函数的调用
cout << p2.age << endl;
cout << p3.age << endl;
//2.显示法
person p4;
person p5 = person(10);//有参构造函数
person p6 = person(p2);//拷贝构造函数
//person(10)匿名对象,执行完这行代码后就会被销毁. 放到等号右面就有名了
//不要利用拷贝构造函数,初始化匿名对象 编译器会认为person(p6)等价于person p6,对象声明
//3.隐式转换法
person p7 = 10;//相当于写了person p7 = person(10);有参构造函数
person p8 = p7;//拷贝构造
}
int main()
{
test01();
}
拷贝函数调用时机
#include<iostream>
using namespace std;
class person {
public:
person()
{
cout << "person默认构造函数调用" << endl;
}
person(int age)
{
Age = age;
cout << "person有参构造函数调用" << endl;
}
person(const person& p)
{
Age = p.Age;
cout << "person拷贝构造函数调用" << endl;
}
~person()
{
cout << "person析构函数调用" << endl;
}
int Age;
};
//拷贝构造函数的调用时机
//1.使用一个已经创建好的对象来初始化一个新对象
void test01()
{
person p1(20);
person p2(p1);
cout << "p2的年龄为:" << p2.Age << endl;
}
//2.值传递的方式给函数传参
void dowork(person p)//值传递创建临时副本,也会发生拷贝构造函数调用,函数结束时销毁p
{
}
void test02()
{
person p;
dowork(p);
}
//3.值传递的方式返回局部对象
person dowork2()
{
person p3;
return p3;
}//函数结束时销毁,但会拷贝p3返回给p4
void test03()
{
person p4 = dowork2();
}
int main()
{
//test01();
test02();
//test03();
}
返回对象(值):拷贝构造函数会被调用,创建一个新的副本返回,原对象不变(但函数内部可能已修改原对象)。
person personaddage(person & p) // 返回 person,而不是 person&
{
this->age += p.age;
return *this; // 这里会发生什么?
}
返回引用:不调用拷贝构造函数,直接返回原对象。
person& personaddage(person & p) // 返回引用
{
this->age += p.age;
return this; // 返回的是原对象的引用
}
浅拷贝
浅拷贝只会复制栈内存中的内容:
对基本类型:直接复制值(和普通赋值没区别);对引用类型:只复制堆内存的地址指针,不会复制堆里的真实数据。
影响:
数据互相篡改:多个对象的指针指向同一块堆内存,修改一个对象的堆数据,其他对象也会受影响;双重释放(double free):对象析构时,都会调用delete释放同一块堆内存,直接触发程序崩溃。
深拷贝
深拷贝会逐层遍历原数据,对每一层的数据都做完整复制:
对基本类型:直接复制值;对引用类型:重新在堆内存开辟一块新空间,复制原堆里的真实数据,栈内存新的地址指针
比如person有成员变量intp=new int (5);
person(const personTom) {p=new int(Tom)}
class person
{
public:
person(int a,int h)
{
age = a;
height = new int(h);
cout << "有参构造函数的调用" << endl;
}
// 格式:
person(const person& p)
{
if(p.height!=nullptr){//防止解引用空指针
//height=p.height;//编译器默认实现
height = new int((p.height)); //防止解引用空指针
}
else{height=nullptr;}
age = p.age;
cout << "拷贝构造函数的调用" << endl;
}
~person()
{
if (height != NULL)
{
delete height;
height = NULL;
}
cout << "析构函数的调用" << endl;
}
int GetAge()
{
return age;
}
int GetHeight()
{
return *height;
}
private:
int age;
int *height;
};
int main()
{
person p1(18, 160);
cout << "p1的年龄为:" << p1.GetAge() << " p1的身高为:" << p1.GetHeight() << endl;
person p2(p1);
cout << "p2的年龄为:" << p2.GetAge() << " p2的身高为:" << p2.GetHeight() << endl;
return 0;
}
浅拷贝引发错误:
#include<iostream>
using namespace std;
class person
{
public:
person()
{
cout << "person constructor" << endl;
}
person(int age, int height)
{
Age = age;
Height = new int(height);
cout << "有参构造函数" << endl;
}
~person()
{
//析构代码,将堆区开辟的内存释放掉
if (Height != NULL)
{
delete Height;//释放内存
Height = NULL;//将指针置空,防止野指针出现
}
cout << "析构函数" << endl;
}
int Age;
int* Height;//由于要开辟内存,这里使用指针,上方用指针接受堆区的数据
};
void test01()
{
person p1(18, 180);
cout << "p1的年龄为:" << p1.Age << " 身高为"<<*p1.Height<<endl;
person p2(p1);
cout << "p2的年龄为:" << p2.Age << " 身高为" << *p2.Height << endl;
}
int main()
{
test01();
}
由于p2后进堆区,先进行内存释放,会把公共的堆区请求内存释放掉,此后p1再释放为非法操作(为编译器自行提供的拷贝函数)。解决:自己写拷贝构造函数
如果属性有在堆区开辟的,要自己提供拷贝函数,防止浅拷贝(简单的赋值)的问题
person(const person& p)
{
cout << "person拷贝构造函数" << endl;
Age = p.Age;
//Height =p.Height;编译器默认实现这行代码
//深拷贝操作:重新创建内存
Height = new int(*p.Height);
} 自己提供拷贝构造
总结:
函数名和类名完全相同(和普通构造函数一样);
唯一的参数是「当前类的 const 引用」(格式:类名(const 类名& 形参名))。
拷贝构造函数属于类的成员函数,遵循 “类内声明、类外定义”(简单类可直接类内定义),只读不修改源对象,所以参数必须加 const,且必须传引用
加「const」:保护源对象,防止被意外修改传「引用」:避免无限递归调用拷贝构造函数
传值时编译器会自动创建实参的临时拷贝,而创建这个临时拷贝又会调用拷贝构造函数,最终导致无限递归,编译器直接报错。
<类名> <对象名2>(<对象名1>);
<类名> <对象名2> = <对象名1>;
C++ 中拷贝构造函数调用时机通常有三种情况
场景 1:直接用一个对象初始化另一个新对象场景 2:函数的形参是类的值传递场景 3:函数返回值是类的值传递
C++标准支持带有一个参数的构造函数,将参数类型隐式转换为相应的类类型。
class A
{
public:
A(int x) { num = x; } // 单参构造
int num;
};
int main()
{
A a = 100; // ✅ 合法!隐式转换
// 编译器自动:100 → 调用A(int)构造 → 生成临时对象赋值
return 0;
}
加 explicit 禁止隐式转换
class A
{
public:
explicit A(int x) { num = x; }
int num;
};
int main()
{
A a = 100; // ❌ 编译报错,禁止隐式转换
A b(100); // ✅ 合法,显式调用构造
A c = A(200);// ✅ 合法,手动显式构造
return 0;
}
委托构造函数
类中包含多个构造函数
一个构造函数在其初始化列表中调用了另一个构造函数,即将构造工作委托给另一个构造函数
class Box
{
double length;
double width;
double height;
public:
Box(double lv,double wv,double hv):length{lv},width{wv}, height{hv}
{}
Box(double side):Box(side,side,side)
{}
};
析构函数
#include <iostream>
using namespace std;
// 1、构造函数分类
// 按照参数分类分为 有参和无参构造 无参又称为默认构造函数
// 按照类型分类分为 普通构造和拷贝构造
class Person {
public:
// 无参(默认)构造函数
Person() {
cout << "无参构造函数!" << endl;
}
// 有参构造函数
Person(int a) {
age = a;
cout << "有参构造函数!" << endl;
}
// 拷贝构造函数
Person(const Person& p) {
age = p.age;
cout << "拷贝构造函数!" << endl;
}
// 析构函数
~Person() {
cout << "析构函数!" << endl;
}
public:
int age;
};
// 2、构造函数的调用
// 调用无参构造函数
void test01() {
Person p; // 调用无参构造函数
}
// 调用有参的构造函数
void test02() {
// 2.1 括号法,常用
Person p1(10);
// 注意1:调用无参构造函数不能加括号,如果加了编译器认为这是一个函数声明
// Person p2();
// 2.2 显式法
Person p2 = Person(10);
Person p3 = Person(p2);
// Person(10)单独写就是匿名对象 当前行结束之后,马上析构
// 2.3 隐式转换法
Person p4 = 10; // 等价于 Person p4 = Person(10);
Person p5 = p4; // 等价于 Person p5 = Person(p4);
// 注意2:不能利用 拷贝构造函数 初始化匿名对象 编译器认为是对象声明
// Person p5(p4);
}
int main() {
test01();
// test02();
return 0;
}
#include <cstring>
class Student {
private:
char* _name; // new[] 开辟(字符串)
int* _score; // new 开辟(单个int)
int* _arr; // new[] 开辟(int数组)
public:
Student(const char* name, int score, int arr[], int n) {
// 构造:依次初始化指针(new[]、new、new[])
_name = new char[strlen(name)+1];
strcpy(_name, name);
_score = new int(score);
_arr = new int[n];
for (int i=0; i<n; i++) _arr[i] = arr[i];
}
// 析构:逐个释放,匹配开辟方式
~Student() {
// 释放new[]的_name
if (_name) { delete[] _name; _name = nullptr; }
// 释放new的_score
if (_score) { delete _score; _score = nullptr; }
// 释放new[]的_arr
if (_arr) { delete[] _arr; _arr = nullptr; }
}
// 深拷贝(必写,每个指针都要单独深拷贝)
Student(const Student& s) {
_name = new char[strlen(s._name)+1];
strcpy(_name, s._name);
_score = new int(*s._score);
// 数组拷贝需先知道长度,这里假设存了长度成员_len,省略
_arr = new int[s._len];
for (int i=0; i<s._len; i++) _arr[i] = s._arr[i];
}
// 赋值运算符重载同理,先释放所有指针,再逐个深拷贝
};
栈类型数据结构
课本P229
类的静态成员
静态数据成员
静态数据成员不属于任何对象,属于类本身,内存中仅开辟一份空间,所有该类的对象共享这一个值;普通成员是「对象级」(每个对象一份),静态成员是「类级」(所有对象一份)。声明规则:类内声明 。声明仅为告诉编译器存在该成员,不分配内存,也不能直接初始化(特殊情况除外)
class Person {
private:
static int _totalNum; // 类内声明:加static,指定权限
const static int MAX = 150; // 特殊情况:const static整型可类内声明+初始化
};
class Person {
private:
static int _totalNum; // 类内声明:加static,指定权限
static int MAX;
};
int Person::MAX=0;//(有点类似初始化了两次)
初始化规则:数据类型 类名::静态成员名 = 初始值; int Person::_total = 0;或者通过创建对象的方式初始化(用对象的成员数据调用)访问 / 赋值规则:权限仍受限,区分直接 / 间接静态成员的访问权限(public/private/protected)依然生效,仅初始化操作不受权限限制,访问 / 赋值需遵循权限规则:1. public 静态成员:类外可直接访问 / 赋值直接访问语法:类名::静态成员名(推荐,体现类级特性) 或 对象.静态成员名(语法合法,不直观);2.private/protected 静态成员:类外禁止直接访问 / 赋值
静态函数成员
属于整个类,而非类的某个对象,是类的全局函数:它不依赖于任何类的对象,创建对象前后都能直接调用;
只能访问「静态数据成员」和「静态函数成员」。静态函数成员也受 public/private/protected 访问权限的限制
class Test {
public:
// 类内仅声明,加static
static int add(int a, int b);
};
// 类外定义:必须加「类名::」,不能加static
int Test::add(int a, int b) {
return a + b;
}
访问
// 方式1:类名直接调用(推荐)
Test::showInfo();
int res = Test::add(3, 5); // res=8
// 方式2:通过类的对象调用(语法合法,但不推荐)
Test t;
t.showInfo();
t.add(2, 4); // res=6
作用举例统计类的对象相关信息
class Person {
private:
// 1. 私有静态数据成员:存储统计信息,类外无法直接修改(封装)
static int totalCount; // 累计创建的对象总数(只增不减)
static int aliveCount; // 当前存活的对象数(增/减)
int age; // 普通成员:每个对象独有,不影响统计
public:
// 2. 构造函数:创建对象时执行 → 计数+1
Person(int a = 0) : age(a) {
totalCount++; // 累计数+1
aliveCount++; // 存活数+1
cout << "创建Person对象,年龄:" << age << endl;
}
// 3. 析构函数:销毁对象时执行 → 存活数-1
~Person() {
aliveCount--; // 仅存活数-1(累计数不变)
cout << "销毁Person对象,年龄:" << age << endl;
}
// 4. 公共静态函数成员:类级接口,获取私有统计值(无需创建对象)
static int getTotalCount() {
return totalCount;
}
static int getAliveCount() {
return aliveCount;
}
};
// 5. 类外初始化静态数据成员:必须步骤,初始值都为0
int Person::totalCount = 0;
int Person::aliveCount = 0;
静态成员变量及存储
#include<iostream>
using namespace std;
//静态成员函数
//所有对象共享同一个函数,静态成员函数只能访问静态成员变量
class person {
public:
static void func()
{
m_A = 10;//共用同一份,不会因无法区分是哪个对象而报错
cout << "static func调用了" << endl;
}
static int m_A;
//访问权限 private类外访问不到
};
int person::m_A = 100;
void test02()
{
//1.通过对象访问
person p;
p.func();
//2.通过类名访问
person::func();
}
int main()
{
test02();
}
//空对象的大小为1,编译器会给空对象分配一个字节的空间,保证每个对象都有一个独一无二的地址
//成员变量和成员函数分开存储,只有非静态成员变量属于类的对象上(占存储空间)
静态成员函数:可以访问静态成员变量,不可以访问非静态成员变量(属于特定的对象,无法区分是哪一个对象的属性)。所有对象共享同一个函数
静态成员变量:所有对象共享同一份数据,编译阶段就分配内存,类内声明,类外初始化。
类的常量成员
常量数据成员
不能在类内直接初始化,也不能在构造函数体内初始化,只能在「构造函数初始化列表」中初始化
常量函数成员
this指针的本质是指针常量,指针的指向是不可以改变的
函数内不能修改成员,只能读取成员
Const Person*const this;
Void showPersono()const{
this->m_A=100;//报错
}
mutable 修饰的成员,可在 const 函数中修改
mutable int salary;
常对象
常量对象必须初始化(const 修饰的变量都必须初始化,对象也不例外);常量对象不能调用普通成员函数(普通成员函数可能修改对象成员,存在风险);常量对象只能调用常量成员函数(只读操作,安全);常量对象可以访问静态成员(静态成员属于类,和对象是否 const 无关)。
#include<iostream>
using namespace std;
//常函数
class person {
public:
//this指针是指针常量,指向是不可修改的
//在成员函数后面加const,修饰this指针,让指针指向的值也不可修改
void showperson() const //const person *const this
{
this->m_B = 100;
}
int m_A;
mutable int m_B;//mutable修饰的成员变量,即使在常函数中也可以修改
};
void test01()
{
person p;
p.showperson();
}
//常对象
void test02()
{
const person p1;
p1.m_B = 100;//在常对象下也可修改
//常对象只能调用常函数,因为普通成员函数可以修改属性
}
int main()
{
}
友元
友元函数
友元 = 破例的 “自己人”,可以直接访问类的 private /protected。
友元函数的关键是在类内部用friend关键字声明(声明位置不影响,可在public/private/protected区,推荐放public区方便阅读),在类外部定义(无需加类名::,因为它不是成员函数)
friend 返回值类型 函数名(参数列表);
友元关系是单向的,A是B的友元!=B是A的友元
友元关系不能传递
#include<iostream>
#include<string>
using namespace std;
class building {
//全局函数做building的好朋友,可以访问building中的私有成员
friend void goodboy(building* build);
public:
building()
{
m_sittingroom = "sitting room";
m_bedroom = "bed room";
}
public:
string m_sittingroom;
private:
string m_bedroom;
};
//全局函数
void goodboy(building* build)
{
cout << "all func " << build->m_sittingroom << endl;
cout << "all func " << build->m_bedroom << endl;
};
void test01()
{
building build;
goodboy(&build);
};
int main()
{
test01();
}
友元类
普通类:别人家的陌生人,只能碰你家public的东西;
友元函数:你单独给了钥匙的一个陌生人,能进你家碰所有东西;
友元类:你给了一整个家庭钥匙,这个家庭的每一个人(所有成员函数)都能进你家碰所有东西。
// 类A:授权方(被访问的类),给类B开权限
class A {
// 关键:声明类B是A的友元类,这是唯一的授权操作
friend class B;
private:
int a_pri = 10; // A的私有成员
protected:
int a_pro = 20; // A的保护成员
public:
int a_pub = 30; // A的公有成员
};
// 类B:被授权方(友元类),无需任何特殊声明,直接访问A的所有成员
class B {
public:
// B的任意成员函数,都能直接访问A的所有成员
void visitA(A& a) {
cout << a.a_pri << endl; // 访问A的private
cout << a.a_pro << endl; // 访问A的protected
cout << a.a_pub << endl; // 访问A的public
}
// B的私有成员函数也能访问A,因为授权的是整个B类
private:
void privateVisit(A& a) {
cout << a.a_pri + a.a_pro << endl;
}
};
#include<iostream>
#include<string>
using namespace std;
//类作友元
class Building;
class goodgay {
public:
goodgay();
void visit();
Building * building;
};
class Building {
friend class goodgay;//goodgay是本类的好朋友,可以访问私有成员
public:
Building();
public:
string m_sittingroom;
private:
string m_bedroom;
};
//类外写成员函数
Building::Building()
{
m_sittingroom = "keting";
m_bedroom = "woshi";
}
goodgay::goodgay()
{
//创建建筑物对象
building = new Building;
}
void goodgay::visit()
{
cout << "goodgay visit "<< building->m_sittingroom << endl;
cout << "goodgay visit " << building->m_bedroom << endl;
}
void test01()
{
goodgay g;
g.visit();
}
int main()
{
test01();
}
类与类之间的关系
一个类作为另一个类的成员
注:这个地方是重点,尤其是构造和析构知识点
构造函数格式:类名 (参数总表):初始化符表{函数体}
Person (int a,int b,int c,int d,int name):building(a,b),car(c,d){this->name=name;}
//当其他的类对象作为本类成员,构造时先构造类对象,再构造自身(先把外来构造好,再完善自己的构造)
//析构顺序与构造顺序相反,先析构自身,再析构类对象
#include<iostream>
#include<string>
using namespace std;
class phone
{
public:
phone(string phname)
{
pname = phname;
}
string pname;
};
class person
{
//类对象作为类成员
public:
person(string name, string phname) :m_name(name),m_phone(phname)
{
}
string m_name;
phone m_phone;
};
//当其他的类对象作为本类成员,构造时先构造类对象,再构造自身
//析构顺序与构造顺序相反,先析构自身,再析构类对象
void test01()
{
person p("张三", "华为");
cout << p.m_name << "的手机是" << p.m_phone.pname << endl;
}
int main()
{
test01();
}
嵌套类
嵌套类只是「类型上的嵌套定义」,并不是「对象上的包含关系」,每一个嵌套类的对象,并不会天然绑定 / 包含一个外部类的对象,两者的对象是完全独立的。
创建格式:
大类::被嵌套的类 类名;
运算符的重载
如下5个运算符不可重载:
. :: ?: .* sizeof
只能以类成员而不能以友元身份重载的运算符:
= ( ) [ ] -> typedef
我的习惯:加减乘除左移右移友元函数,其余统统类成员
不能改变运算符的优先级和操作数个数(+是双目运算符,必须两个操作数);不能重载 C++ 的内置运算符含义(比如不能让int + int变成减法);重载建议返回新对象,而不是修改原对象(符合a = b + c的常规逻辑,b 和 c 本身不变)
加号+加减乘除
成员函数
全局函数(友元)
#include <iostream>
using namespace std;
// 自定义测试类:二维坐标类
class Point {
private:
int x; // x坐标
int y; // y坐标
public:
// 构造函数:初始化x、y,带默认参数
Point(int x_ = 0, int y_ = 0) : x(x_), y(y_) {}
// 1. 成员函数重载+:对象 + 对象
Point operator+(const Point& other) {
Point temp;
temp.x= this->x + other.x;
temp.y=this->y + other.y;
return temp;
}
// 2. 成员函数重载+:对象 + 数值
Point operator+(int num) {
Point temp;
temp.x = this->x + num;
temp.y = this->y + num;
return temp;
}
//但是无法写数值+对象
// 3. 友元声明:所有+重载函数(访问私有成员)
friend Point operator+(const Point& p1, const Point& p2); // 对象+对象
friend Point operator+(const Point& p, int num); // 对象+数值
friend Point operator+(int num, const Point& p); // 数值+对象
// 辅助函数:打印坐标,查看结果
void print(const string& name) const {
cout << name << " = (" << x << ", " << y << ")" << endl;
}
};
//不能返回类的引用,因为返回的是函数内部创建的临时对象 temp,它出了函数就会被销毁!
// 4. 全局友元重载+:对象 + 对象
Point operator+(const Point& p1, const Point& p2) {
Point temp = p1;
temp.x = p1.x + p2.x;
temp.y = p1.y + p2.y;
return temp;
}
// 5. 全局友元重载+:对象 + 数值
Point operator+(const Point& p, int num) {
Point temp = p;
temp.x += num;
temp.y += num;
return temp;
}
// 6. 全局友元重载+:数值 + 对象(复用对象+数值,实现交换律)
Point operator+(int num, const Point& p) {
return p + num; // 直接复用,避免重复代码
}
// 主函数测试所有场景
int main() {
Point p1(1, 2), p2(3, 4);
// 测试1:对象 + 对象
Point p3 = p1 + p2;
p3.print("p1 + p2"); // 输出(4, 6)
// 测试2:对象 + 数值
Point p4 = p1 + 5;
p4.print("p1 + 5"); // 输出(6, 7)
// 测试3:数值 + 对象(交换律)
Point p5 = 5 + p1;
p5.print("5 + p1"); // 输出(6, 7)
return 0;
}
形参规则:两个形参都用const&修饰 ——const保证不修改对象,&避免对象拷贝,提升效率;
左移<< 右移>>
只能用全局友元函数实现
ostream& operator<<(ostream& cout, const Point& p) {
// 向输出流os中写入自定义的打印格式,可随意修改
cout << "(" << p.x << ", " << p.y << ")";
return cout;
// 必须返回输出流引用,支持链式调用
}
istream& operator>>(istream& cin,const Point& p){
cin>>......
return cin;
}
cout的类型是输出流对象,全局只有一个,不能拷贝
如果返回值是void则无法链式调用cout<<p<<endl;
递增++
前置递增(++a)
前置递增能链式调用
// 前置递增:成员函数重载
MyInt& operator++() {
val++; // 第一步:自身值+1
return *this; // 第二步:返回修改后的自身(引用)
}
后置递增(a++)
后置递增不能链式调用
// 后置递增:成员函数重载(int是占位参数)
MyInt operator++(int) {
MyInt temp = *this; // 第一步:保存修改前的原始值(临时对象)
val++; // 第二步:自身值+1
return temp; // 第三步:返回原始值(值传递,临时对象拷贝)
}
赋值=
(如果你不写,编译器会默认生成一个,但是是浅拷贝)
赋值运算符不能用友元函数重载,它必须作为类的成员函数来重载。
//赋值运算符的重载
class person
{
public:
person(int a)
{
age=new int(a);
}
~person()
{
if (age != NULL)
{
delete age;
age = NULL;
}
}
//重载赋值运算符以避免浅拷贝带来的问题
person& operator=(const person& p)
{
//age=p.age;//编译器默认实现
if (age != NULL)
{
delete age;
age = NULL;
}
age = new int(*p.age);
//返回自身使能够链式调用
return *this;
}
int *age;
};
int main()
{
person p1(10);
person p2(20);
person p3(30);
p3=p2 = p1;
cout << *(p2.age) << endl;//10
cout << *(p3.age) << endl;//10
return 0;
}
赋值运算符重载 标准格式
// 强制固定格式:ClassName& operator=(const ClassName& 形参)
ClassName& ClassName::operator=(const ClassName& other) {
// 步骤1:处理自赋值(强制写,避免野指针)
if (this == &other) {
return *this;
}
// 步骤2:释放当前对象自身的所有堆内存(强制写,避免内存泄漏)
// 对每个指针成员:if(指针) { delete/delete[] 指针; 指针 = nullptr; }
// 步骤3:深拷贝核心(按需编写)
// 1. 为当前对象的所有指针成员,重新开辟堆内存;
// 2. 复制other对象中对应指针指向的堆数据;
// 3. 基本类型成员直接赋值(other.成员名);
// 步骤4:返回*this(强制写,支持链式赋值)
return *this;
}
格式强制要求(缺一不可)
返回值必须是 ClassName&(类的引用):支持链式赋值(如a = b = c;),避免返回值生成临时对象损耗性能;函数名必须是 operator=(运算符重载的语法);参数必须是 const ClassName&(原因同拷贝构造);必须处理自赋值(if (this == &other)):防止a = a;时,先释放自身堆内存,后续复制数据访问野指针;必须先释放自身堆内存:否则当前对象的堆内存会成为「内存泄漏」,无法被释放;最后必须返回 *this:this是当前对象的地址,*this是当前对象本身,配合引用返回实现链式赋值;访问权限:必须放在 public 下。
关系== !=
//关系运算符重载 == !=
class person
{
public:
person(string s,int a):name(s),age(a)
{
}
bool operator==(person& p)
{
if (this->name == p.name && this->age == p.age)
{
return true;
}
else
return false;
}
string name;
int age;
};
int main()
{
person p1("xi",10);
person p2("xi",20);
if (p1 == p2)
{
cout << "p1和p2相等" << endl;
}
else
cout << "p1和p2不相等" << endl;
return 0;
}
下标[]
Node List::operator[](int index)
{
int count = 0;
Node *curr = head;
while(curr != nullptr){
if(index == count)
return *curr;
count++;
curr = curr->next;
}
return nullptr;
}
一个矩阵[]运算符重载的实例
#include<iostream>
using namespace std;
class ma {
int** data;
int n;
int m;
public:
//构造函数定长度
ma(int n,int m) : n(n), m(m) {
data = new int* [n];
for (int i = 0; i < n; i++) {
data[i] = new int[m];
}
}
//友元重载
friend istream& operator>>(istream& cin, ma& ma);
friend ostream& operator<<(ostream& cout, ma& m);
//成员函数重载,返回指针,可二重
int* operator[](int idex) {
return data[idex];
}
};
ostream& operator<<(ostream& cout, ma& m)
{
for (int i = 0; i <m.n; i++)
{
for (int j = 0; j < m.m; j++)
{
cout << m.data[i][j] << "\t";
}
cout << endl;
}
return cout;
}
istream& operator>>(istream& cin, ma& ma) {
for (int i = 0; i < ma.n; i++) {
for (int j = 0; j < ma.m; j++) {
cin >> ma.data[i][j];
}
}
return cin;
}
int main() {
int n, m, a, b;
cin >> n >> m >> a >> b;
ma m1(n, m);
ma m2(n, m);
cin >> m1 >> m2;
cout << m1[1][1] << endl;
cout << m1;
}
函数调用运算符重载(仿函数)
//函数调用运算符重载
class MyPrint
{
public:
void operator()(string text)//与函数调用长得差不多,所以被称为仿函数
{
cout << text << endl;
}
};
void print(string text)
{
cout << text << endl;
}
int main()
{
MyPrint m1,m2;
m1("xiyang");
m2("xiyang");
return 0;
}
回溯法
#include <iostream>
#include <iomanip>
#include<process.h>
using namespace std;
const int m = 12, p = 15;
const int maxsize = m * p;
struct offsets {
int a, b;
};
const offsets move[8] = {
{-1,0}, {-1,1}, {0,1}, {1,1},
{1,0}, {1,-1}, {0,-1}, {-1,-1}
};
struct items {
int x, y;
int dir;
};
void printDir(int dir) {
char dirName[8][3] = { "N", "NE", "E", "SE", "S", "SW", "W", "NW" };
cout << setw(2) << dirName[dir];
}
class stack {
items data[maxsize];
int top;
public:
stack() { top = 0; }
bool empty() { return (top == 0) ? true : false; }
void push(items it);
items pop(void);
void print(void);
int gettop(void) { return top; }
};
void stack::push(items it) {
if (top == maxsize) {
cout << "stack is full!" << endl;
return;
}
data[top].x = it.x;
data[top].y = it.y;
data[top].dir = it.dir;
top++;
}
items stack::pop(void) {
if (top == 0) {
cout << "stack is underflow!" << endl;
exit(0);
}
top--;
return data[top];
}
void stack::print(void) {
cout << "top=" << top << endl;
for (int i = 0; i < top; i++) {
cout << "step" << i + 1 << ": (" << data[i].x << "," << data[i].y << "), ";
printDir(data[i].dir);
cout << "\t";
if ((i + 1) % 3 == 0) cout << endl;
}
}
bool mark[m][p];
int maze[m][p] = {
{0,1,0,0,0,1,1,0,0,0,1,1,1,1}, {1,0,0,0,1,1,0,1,1,0,0,1,1,1},
{0,1,1,0,0,0,0,1,1,1,0,0,1,1}, {1,1,0,1,1,1,0,1,0,1,1,0,0},
{1,1,0,1,0,0,1,0,1,1,1,1,1,1}, {0,0,1,1,0,1,1,0,1,0,0,1,0,1},
{0,0,1,1,0,1,1,0,1,0,0,1,0,1}, {0,1,1,1,0,0,1,1,1,1,1,1,1},
{0,1,1,0,1,1,0,1,1,1,1,0,1}, {1,1,0,0,0,1,1,0,1,0,0,0,0},
{0,0,1,1,1,1,0,0,0,1,1,1,0}, {1,0,1,0,0,1,1,1,0,1,1,1,0}
};
void path(int m, int p) {
mark[0][0] = true;
items temp = { 0, 0, 2 };
stack mazepath;
mazepath.push(temp);
while (!mazepath.empty()) {
temp = mazepath.pop();
int i = temp.x;
int j = temp.y;
int d = temp.dir;
while (d < 8) {
int g = i + move[d].a;
int h = j + move[d].b;
if (g < 0 || h < 0 || g >= m || h >= p) {
d++;
}
else {
if (g == m - 1 && h == p - 1) {
mazepath.print();
int ind = mazepath.gettop();
cout << "step" << ind + 1 << ": (" << i << "," << j << "), ";
printDir(d);
cout << endl;
return;
}
if (!maze[g][h] && !mark[g][h]) {
mark[g][h] = true;
temp.x = i;
temp.y = j;
temp.dir = d;
mazepath.push(temp);
i = g;
j = h;
d = 0;
}
else {
d++;
}
}
}
}
cout << "no path in the maze" << endl;
}
void main() {
for (int i = 0; i < m; i++)
for (int j = 0; j < p; j++)
mark[i][j] = false;
path(m, p);
}
运算符重载实例总结
注:另一个版本的运算符重载笔记()和上面知识点是一样的,只是笔记风格不同。
注:
对于 公有成员,任何外部函数(全局函数、其他类的成员函数等)只要能访问到对象,就可以直接读取或修改它们。友元的作用是突破 private / protected 的限制。只有当数据成员是私有或保护的时候,外部函数才必须通过友元声明来获得访问权限。
1.加号+
#include<iostream>
using namespace std;
class Person {
public:
int m_A;
int m_B;
//成员函数重载
// 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;
// }
};
//全局函数重载
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;
p3 = p1 + p2;
cout << "p3.m_A = " << p3.m_A << endl;
cout << "p3.m_B = " << p3.m_B << endl;
//运算符重载,也可以发生函数重载
Person p4;
p4 = p1 + 100;
cout << "p4.m_A = " << p4.m_A << endl;
cout << "p4.m_B = " << p4.m_B << endl;
}
int main()
{
test01();
}
//成员函数重载本质调用:
//Person p3=p1.operator+(p2);
//全局函数重载本质调用:
//Person p3=operator+(p1, p2);
注意:对于内置数据类型的表达式的运算符是不可能改变的
2.左移<<
#include<iostream>
using namespace std;
//左移运算符重载
class Person {
public:
int m_A;
int m_B;
//利用成员函数重载左移运算符
//不会利用成员函数重载左移运算符,因为无法实现cout在左侧。
// 先有对象调用,所以p在左面。要用全局函数
};
//利用全局函数重载左移运算符
void operator<<(ostream &cout, Person &p) //确保全局只有一个cout,给它加上&
{
cout << "m_A=" << p.m_A << " m_B=" << p.m_B << endl;
}
//本质:operator<<(cout,p) ,简化:cout<<p
//注:由于引用的本质是起别名,指向同一个内存空间,所以上面cout的名字可以更改,如out,也不报错。
//若改为ostream operator<<(ostream &cout, Person &p),函数末尾加上return cout,
// 则可以实现链式调用cout<<p1<<p2;
void test01()
{
Person p;
p.m_A = 10;
p.m_B = 10;
cout << p;
}
int main()
{
test01();
}
注:cout属于ostream类型
private数据,用公有成员函数配合友元进行访问
#include<iostream>
using namespace std;
class Person {
friend void operator<<(ostream& cout, Person& p);
private:
int m_A;
int m_B;
public:
public:
Person(int a, int b)
{
m_A = a;
m_B = b;
}
};
void operator<<(ostream &cout, Person &p)
{
cout << "m_A=" << p.m_A << " m_B=" << p.m_B << endl;
}
void test01()
{
Person p(10,10);
cout << p;
}
int main()
{
test01();
}
3.递增++
#include<iostream>
using namespace std;
//重载递增运算符
class MyInteger {
friend ostream& operator<<(ostream& cout, MyInteger myint);
private:
int m_num;
public:
MyInteger()
{
m_num = 0;
}
//重载前置++
MyInteger &operator++() //返回引用为了一直对一个数据进行递增操作
{
m_num++;//先进行++运算
return *this;//再返回对象本身
}
//重载后置++
MyInteger operator++(int) //int代表占位参数,用于区分前置和后置递增
{
//先记录当时结果
MyInteger temp = *this;
//后递增
m_num++;
//最后返回记录结果
return temp;
}//后置递增返回值为对象本身,不能返回引用,因为返回的是一个临时对象,函数结束后会被销毁。
};
//重载左移
ostream &operator<<(ostream& cout, MyInteger myint) //拷贝,避免&导致返回的临时对象被销毁而引发错误
{
cout << myint.m_num;
return cout;
}
void test01()
{
MyInteger myint;
cout <<++(++myint) << endl;
cout << myint << endl;
}
void test02()
{
MyInteger myint;
cout << myint++ << endl;
cout << myint << endl;
}
int main()
{
test01();
test02();
}
后置++(如 obj++)对应的重载函数必须有一个额外的 int 参数,这个 int 纯粹用于区分签名,不需要传递实际值,通常也不使用。
如果运算符在操作数前面(前置),就匹配无参版本。如果运算符在操作数后面(后置),就匹配带 int 参数的那个版本。
前置 ++ 返回左值(对象本身),可以用引用接收。后置 ++ 返回右值(临时对象),不能用引用接收,只能用值传递或const 引用(推荐 const 引用)接收。
#include <iostream>
using namespace std;
class Num {
private:
int val;
public:
// 构造函数
Num(int v = 0) : val(v) {}
// 打印值
void show() const {
cout << val << endl;
}
// 1. 前置 ++ 重载
Num& operator++() {
val++; // 先自增
return *this; // 返回自身引用
}
// 2. 后置 ++ 重载,int只是占位区分,不用传参
Num operator++(int) {
Num temp = *this; // 保存原来的值
val++; // 对象自身自增
return temp; // 返回旧值副本
}
};
int main() {
Num a(10);
cout << "前置++:";
++a;
a.show(); // 11
Num b(20);
cout << "后置++输出原值:";
(b++).show(); // 打印20(返回的是自增前的临时对象)
cout << "后置++后对象本身:";
b.show(); // 21
return 0;
}
4.赋值=
#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) //返回引用才是真的自身,返回值会拷贝副本
{
//编译器提供了一个默认的operator=,但提供的是浅拷贝,析构重复释放引发问题
//m_age=p.m_age
//要让p2和p1不指向同一块内存,应先判断是否有属性在堆区,如果有先释放干净,再深拷贝
if (m_age != NULL)
{
delete m_age;
m_age = NULL;
}
m_age = new int(*p.m_age);
//返回对象本身
return *this;
}
int* m_age;
};
void test01()
{
person p1(18);
person p2(20);
person p3(30);
p3 = p2 = p1;//赋值
cout << "p1的年龄为:" << *p1.m_age << endl;
cout << "p2的年龄为:" << *p2.m_age << endl;
cout << "p3的年龄为:" << *p3.m_age << endl;
}
int main()
{
test01();
}
5.关系==/!=
#include<iostream>
#include<string>
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;
}
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;
}
}
string m_name;
int m_age;
};
void test01()
{
person p1("tom", 18);
person p2("jerry", 18);
if (p1==p2)
{
cout << "p1和p2相等" << endl;
}
else {
cout << "p1和p2不相等" << endl;
}
if(p1!=p2)
{
cout << "p1和p2不相等" << endl;
}
}
int main()
{
test01();
}
6.函数调用
#include<iostream>
#include<string>
using namespace std;
//重载函数调用运算符
class myprint{
public:
void operator()(string test)
{
cout << test << endl;
}
};
void test01()
{
myprint mp;
mp("hello world");//由于使用上非常类似于函数调用,所以称为仿函数
}
int main()
{
test01();
}
OJ对应习题
#include<iostream>
#include<cmath>
using namespace std;
int classify(int up,int down){
int u=abs(up);
int d=abs(down);
if(u==0)
{
return 1;
}
else{
int min=u<d?u:d;
for(int i=min;i>0;i--)
{
if(u%i==0&&d%i==0)
{
return i;
}
}
}
}
class Rational{
public:
int a;
int b;
void getvalue(int val1,int val2){
a=val1;
b=val2;
}
Rational operator++(int)
{
Rational p=*this;
this->a=this->a+this->b;
return p;
}
void change(){
int curr=a;
a=b;
b=curr;
if(b==1)
{
cout<<a;
}
else{
if(b==-1)
{
cout<<-a;
}
else{
if(b<0)
{
cout<<-a<<"/"<<-b;
}
else{
cout<<a<<"/"<<b;
}
}
}
}
};
Rational operator+(Rational &p1,Rational &p2)
{
Rational p;
p.b=p1.b p2.b ;
p.a=p1.ap2.b+p2.a*p1.b;
int temp=classify(p.a,p.b);
p.a/=temp;
p.b/=temp;
return p;
}
Rational operator-(Rational &p1,Rational &p2)
{
Rational p;
p.b=p1.b p2.b ;
p.a=p1.ap2.b-p2.a*p1.b;
int temp=classify(p.a,p.b);
p.a/=temp;
p.b/=temp;
return p;
}
Rational operator*(Rational &p1,Rational &p2)
{
Rational p;
p.a=p1.ap2.a;
p.b=p1.bp2.b;
int temp=classify(p.a,p.b);
p.a/=temp;
p.b/=temp;
return p;
}
Rational operator/(Rational &p1,Rational &p2)
{
Rational p;
p.a=p1.ap2.b;
p.b=p1.bp2.a;
int temp=classify(p.a,p.b);
p.a/=temp;
p.b/=temp;
return p;
}
void operator<<(ostream &cout,Rational p)
{
if(p.a==0)
{
cout<<"0";
}
else{
if(p.b==1)
{
cout<<p.a;
}
else{
if(p.b==-1)
{
cout<<-p.a;
}
else{
if(p.b<0)
{
cout<<-p.a<<"/"<<-p.b;
}
else{
cout<<p.a<<"/"<<p.b;
}
}
}
}
}
int main(){
int a1,b1,a2,b2;
cin>>a1>>b1>>a2>>b2;
Rational R1;
Rational R2;
R1.getvalue(a1,b1);
R2.getvalue(a2,b2);
Rational store1=R1;
Rational store2=R2;
Rational Rplus=R1+R2;
cout<<Rplus;
cout<<endl;
Rational Rminus=R1-R2;
cout<<Rminus;
cout<<endl;
Rational Rtimes=R1*R2;
cout<<Rtimes;
cout<<endl;
Rational Rabstract=R1/R2;
cout<<Rabstract;
cout<<endl;
R1++;
cout<<R1;
cout<<" ";
R2++;
cout<<R2;
cout<<endl;
store1.change();
cout<<" ";
store2.change();
cout<<endl;
return 0;
}
#142matrix类
#include<iostream>
using namespace std;
class matrix {
private:
int a[3][3];
public:
void setmatrix();
void print();
friend matrix operator+(matrix m1, matrix m2);
friend matrix operator-(matrix m1, matrix m2);
friend matrix operator*(matrix m1, matrix m2);
friend ostream& operator<<(ostream& cout, matrix m);
};
matrix operator+(matrix m1, matrix m2) {
matrix res;
for (int i = 0; i < 3; i++) {
for(int j=0;j<3;j++){
res.a[i][j] = m1.a[i][j] + m2.a[i][j];
}
}
return res;
}
matrix operator-(matrix m1, matrix m2) {
matrix res;
for (int i = 0; i < 3; i++) {
for (int j = 0; j < 3; j++) {
res.a[i][j] = m1.a[i][j] -m2.a[i][j];
}
}
return res;
}
matrix operator*(matrix m1, matrix m2) {
matrix res;
for (int i = 0; i < 3; i++) {
for (int j = 0; j < 3; j++) {
res.a[i][j] = m1.a[i][0] * m2.a[0][j] + m1.a[i][1] * m2.a[1][j] + m1.a[i][2] * m2.a[2][j];
}
}
return res;
}
ostream& operator<<(ostream& cout, matrix m) {
for (int i = 0; i < 3; i++) {
for (int j = 0; j < 3; j++) {
cout << m.a[i][j];
if (j != 2) {
cout << " ";
}
}
cout << endl;
}
return cout;
}
void matrix::setmatrix() {
for (int i = 0; i < 3; i++) {
for (int j = 0; j < 3; j++) {
cin >> a[i][j];
}
}
return;
}
void matrix::print(){
for (int i = 0; i < 3; i++) {
for (int j = 0; j < 3; j++) {
cout<< a[i][j];
if (j != 2) {
cout << " ";
}
}
cout << endl;
}
return;
}
int main() {
matrix m1, m2;
m1.setmatrix();
m2.setmatrix();
matrix res1, res2, res3;
res1 = m1 + m2;
res2 = m1 - m2;
res3 = m1 * m2;
cout << res1 << res2 << res3;
return 0;
}
#89分数类
cin 读取数据时,默认会以「空白符(空格 / 回车 / 制表符)」作为分隔符,但对于 12/24 这种无空白符的字符串,我们可以主动指定分隔字符(/),让 cin 按「分子→/→分母」的顺序读取,步骤如下:
cin 读取整数(分子):遇到非数字字符(/)时停止,把前面的数字(12)存入分子变量;cin 读取字符(/):跳过 / 忽略这个分隔符,只需要把它存到一个临时字符变量里即可;cin 读取整数(分母):从/后面继续读取数字(24),存入分母变量。
#include<iostream>
using namespace std;
//辗转相除法求最大公约数
int gongyueshu(int a, int b) {
if (a % b == 0) {
return b;
}
return gongyueshu(b, a % b);
}
//求最大公倍数
int gongbeishu(int a, int b) {
return (a * b) / gongyueshu(a, b);
}
class fraction {
private:
int m_up;//分子
int m_down;//分母
public:
fraction& set();//输入
void tongfenprint();//通分输出
void print();//输出
void yuefen();//约分
friend void tongfen(fraction& a, fraction& b);//通分
fraction upside();//倒数
friend void compare( fraction& a, fraction&b);//比较
friend fraction operator+(const fraction a, const fraction b);
friend fraction operator-(const fraction a, const fraction b);
friend fraction operator*(const fraction a, const fraction b);
friend fraction operator/(const fraction a, const fraction b);
fraction& operator=(const fraction& a);
};
//输入
fraction& fraction::set() {
int up, down;
char p;
cin >> up >> p >> down;
if (down == 0) {
cout << "分母不能为零!" << endl;
exit(1);
}
m_up = up;
m_down = down;
return *this;
}
//通分输出
void fraction::tongfenprint() {
if (m_down == 1) {
cout << m_up << endl;
}
cout << m_up << '/' << m_down << endl;
}
//输出
void fraction::print() {
(*this).yuefen();
if (m_down == 1) {
cout << m_up << endl;
}
else {
cout << m_up << '/' << m_down << endl;
}
}
//约分
void fraction::yuefen() {
int tem = gongyueshu(m_up, m_down);
m_up /= tem;
m_down /= tem;
return;
}
//通分
void tongfen(fraction& a, fraction& b) {
int tem = gongbeishu(a.m_down, b.m_down);
a.m_up = a.m_up * (tem / a.m_down);
b.m_up = b.m_up * (tem / b.m_down);
a.m_down = tem;
b.m_down = tem;
}
//倒数
fraction fraction::upside() {
fraction tem;
tem.m_up = m_down;
tem.m_down = m_up;
return tem;
}
void compare( fraction& a, fraction& b) {
tongfen(a, b);
if (a.m_up > b.m_up) {
cout << '>' << endl;
}
else if (a.m_up == b.m_up) {
cout << '=' << endl;
}
else { cout << '<' << endl; }
}
fraction& fraction::operator= (const fraction& a) {
m_up = a.m_up;
m_down = a.m_down;
return this;
}
fraction operator+(const fraction a, const fraction b) {
fraction tem;
fraction tem_a = a;
fraction tem_b = b;
tongfen(tem_a, tem_b);
tem.m_up = tem_a.m_up + tem_b.m_up;
tem.m_down = tem_a.m_down;
return tem;
}
fraction operator-(const fraction a, const fraction b) {
fraction tem;
fraction tem_a = a;
fraction tem_b = b;
tongfen(tem_a, tem_b);
tem.m_up = tem_a.m_up - tem_b.m_up;
tem.m_down = tem_a.m_down;
return tem;
}
fraction operator(const fraction a, const fraction b) {
fraction tem;
tem.m_up = a.m_up * b.m_up;
tem.m_down = a.m_down * b.m_down;
return tem;
}
fraction operator/(const fraction a, const fraction b) {
fraction tem;
tem.m_up = a.m_up b.m_down;
tem.m_down = a.m_downb.m_up;
return tem;
}
int main() {
int n;
fraction a, b;
cin >> n;
a.set();
b.set();
for (int i = 0; i < n; i++) {
int rule;
cin >> rule;
switch (rule) {
case 1:
fraction t1 = a + b;
t1.print();
break;
case 2:
fraction t2 = a - b;
t2.print();
break;
case 3:
fraction t3 = a * b;
t3.print();
break;
case 4:
fraction t4 = a / b;
t4.print();
break;
case 5:
tongfen(a, b);
a.tongfenprint();
b.tongfenprint();
break;
case 6:
compare(a, b);
break;
case 7:
a.yuefen();
a.print();
break;
case 8:
fraction tem;
tem = a.upside();
tem.print();
break;
}
}
return 0;
}