(B站黑马C++)友元 + 运算符重载

本文详细介绍了C++中的友元机制,包括全局函数、类和成员函数作为友元的实现方式。同时,探讨了运算符重载的概念,通过实例展示了加号、左移、递增、赋值和关系运算符的重载,并讲解了函数调用运算符重载和链式调用的概念。这些内容有助于深入理解C++类的高级特性。

纯粹记录敲代码的过程,1.5倍速,后续遇到bug会回来检索

目录

🔑友元

🌳全局函数做友元

🌳类做友元

🌳成员函数做友元

🔑运算符重载

🌳加号运算符重载

🌳左移运算符重载

🌳递增运算符重载

🌳赋值运算符重载

🌳关系运算符重载

🌳函数调用运算符重载

🔑总结

🌼返回对象 -- 链式调用


🔑友元

🌳全局函数做友元

客厅(Public), 卧室(private), 陌生人只能进客厅,但是闺蜜(友元)可以进卧室
私有属性为了让类外的函数或类访问,需要用到友元
友元关键字:friend
三种实现:
1,全局函数
2,类
3,成员函数

注意这行

//goodGay全局函数是Building的好朋友, 可以访问Building中私有成员(卧室)
friend void goodGay(Building *building);
#include<iostream>
using namespace std;

//建筑物类
class Building
{
    //goodGay全局函数是Building的好朋友, 可以访问Building中私有成员(卧室)
    friend void goodGay(Building *building);

public:
    Building()
    {
        m_SittingRoom = "客厅";
        m_BedRoom = "卧室";
    }

public: //公共字符串属性
    string m_SittingRoom; //客厅

private: //私有字符串属性
    string m_BedRoom; //卧室
};

//全局函数
void goodGay(Building *building)
{   //访问公共属性m_SittingRoom
    cout<<"好基友 全局 正在访问: "<<building->m_SittingRoom<<endl;

    cout<<"好基友 全局 正在访问: "<<building->m_BedRoom<<endl;
}

void test01()
{
    //定义并创建Building类的对象, 即使用Building类定义一个名为building的变量
    Building building;
    goodGay(&building); //将对象指针传递给全局函数goodGay()
}

int main()
{
    test01();

    system("pause");
    return 0;
}
好基友 全局 正在访问: 客厅
好基友 全局 正在访问: 卧室
请按任意键继续. . .

🌳类做友元

注意这行

//GoodGay类是本类的好朋友, 可以访问类中私有成员
friend class GoodGay;
#include<iostream>
using namespace std;

//类做友元

class Building;

class GoodGay
{
public:

    GoodGay();

    void visit(); //参观函数 访问Building中属性

    Building *building; //内部维护一个指针
};

class Building
{
    //GoodGay类是本类的好朋友, 可以访问类中私有成员
    friend class GoodGay;

public:
    Building();

public:
    string m_SittingRoom; //客厅

private:
    string m_BedRoom; //卧室
};

//类外写成员函数
Building::Building() //Building作用域下成员函数
{
    m_SittingRoom = "客厅";
    m_BedRoom = "卧室";
}

GoodGay::GoodGay()
{
    //创建一个建筑物对象
    building = new Building; //new在堆区创建一个对象, building指针指向这个对象
}

void GoodGay::visit()
{
    cout<<"好基友 访问: "<<building->m_SittingRoom<<endl;

    cout<<"好基友 访问: "<<building->m_BedRoom<<endl;
}

void test01()
{
    GoodGay gg; //GoodGay类, 实例化gg对象
    gg.visit();
}

int main()
{
    test01();

    system("pause");
    return 0;
}
好基友 访问: 客厅
好基友 访问: 卧室
请按任意键继续. . .

🌳成员函数做友元

看这行

//告诉编译器 GoodGay类下的visit成员函数作为本类的好朋友
friend void GoodGay::visit();
#include<iostream>
using namespace std;

class Building;

class GoodGay
{
public:
    GoodGay();

    void visit(); //visit函数访问Building中私有成员
    void visit2(); //visit2不可访问Building中私有

    Building *building;
};

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()
{
    building = new Building; //在堆区创建一个Building对象, 并用building指针维护
}

void GoodGay::visit()
{
    cout<<"visit 函数 访问 "<<building->m_SittingRoom<<endl;

    cout<<"visit 函数 访问 "<<building->m_BedRoom<<endl;
}
void GoodGay::visit2()
{
    cout<<"visit2 函数 访问 "<<building->m_SittingRoom<<endl;

    //cout<<"visit2 函数 访问 "<<building->m_BedRoom<<endl;
}

void test01()
{
    GoodGay gg;
    gg.visit();
    gg.visit2();
}

int main()
{
    test01();

    system("pause");
    return 0;
}
visit 函数 访问 客厅
visit 函数 访问 卧室
visit2 函数 访问 客厅
请按任意键继续. . .

🔑运算符重载

运算符重载:
重新定义已有的运算符,赋予新的功能,以适应不同数据类型 

🌳加号运算符重载

加号:
实现两个自定义数据类型的相加运算

#include<iostream>
using namespace std;

//加号运算符重载
class Person
{
public:
    int m_A;
    int m_B;

//    //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;
//    }
};

//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;
} //全局函数重载  放在test01()之前

//函数重载的版本
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 = 30, p1.m_B = 10;

    Person p2;
    p2.m_A = 5, p2.m_B = 10;

    //成员 函数重载的本质 调用
    //Person p3 = p1.operator+(p2);


    //全局 函数重载的本质 调用
    //Person p3 = operator+(p1, p2);


    Person p3 = p1 + p2;

    //运算符重载  也可以发生函数重载(复用函数名)
    Person p4 = p1 + 100;

    cout<<"p3.m_A = "<<p3.m_A<<endl;
    cout<<"p3.m_B = "<<p3.m_B<<endl;

    cout<<"p4.m_A = "<<p4.m_A<<endl;
    cout<<"p4.m_B = "<<p4.m_B<<endl;
}

int main()
{
    test01();

    system("pause");
    return 0;
}
p3.m_A = 35
p3.m_B = 20
p4.m_A = 130
p4.m_B = 110
请按任意键继续. . .

总结1:内置的数据类型(int, double, float...)的表达式运算符,不可更改
总结2:不要滥用运算符重载(比如写了operator+,但是函数里是-)

🌳左移运算符重载

重载左移运算符配合友元,可输出自定义数据类型

friend ostream & operator<<(ostream &cout, Person &p);

👆解释下

在 C++ 中,friend 关键字可以用于声明一个函数或类为另一个类的友元(friend)。类的友元可以直接访问该类的私有成员变量和方法

在这里,我们使用 friend 声明全局函数 operator<<Person 类的友元。这样,在 operator<< 函数中就可以直接访问 Person 类的私有成员 m_Am_B,并将它们输出到屏幕上

具体来说,在 operator<< 函数中,我们使用 cout 对象打印 Person 对象的成员变量,其中 coutostream 类型的对象,用于表示输出流,而 & 表示引用类型,即引用一个 ostream 类型的对象,这样可以避免拷贝构造和析构函数的开销。此外,p 参数是 Person 类型的对象引用,表示要输出的对象

声明一个名为 operator<< 的全局函数,该函数的第一个参数是一个 ostream 对象的引用,表示输出流,第二个参数是一个 Person 对象的引用,表示要输出的对象。返回值是一个 ostream 对象的引用,以支持链式操作

#include<iostream>
using namespace std;

//左移运算符重载
class Person
{
    //使全局函数作为Person类的好朋友, 可以访问Person类私有数据
    friend ostream & operator<<(ostream &cout, Person &p);

public:
    Person(int a, int b)
    {
        m_A = a, m_B = b;
    }

private:
    //利用成员函数重载 左移运算符
    //p.operator<<(cout) 简化版本 p<<cout
    //通常不用成员函数重载左移运算符, 因为无法实现 cout在左侧
    //void operator<<(cout)
    int m_A, m_B;
};

//只能利用全局函数重载左移运算符
//out属于ostream这样一个对象, 输出流
ostream & operator<<(ostream &cout, Person &p) //本质  operator<<(cout, p) 简化 cout<<p
{
    cout<<"m_A = "<<p.m_A<<" m_B = "<<p.m_B<<endl;
    return cout;
}

void test01()
{
    //Person p;
    Person p(10, 7);
//    p.m_A = 10, p.m_B = 7;

    cout<<p<<"hello world"<<endl; //链式, 无限往后追加
}


int main()
{
    test01();

    system("pause");
    return 0;
}
m_A = 10 m_B = 7
hello world
请按任意键继续. . .

🌳递增运算符重载

通过重载递增运算符,实现自己的整型数据

#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; //返回自身, 解引用
    }

    //重载后置++运算符
    //void operator++(int) int代表占位参数, 用以区分前置和后置递增
    //后置返回值 不反悔引用 因为返回的是局部对象 释放掉后会非法操作
    MyInteger operator++(int)
    {
        //先 记录当时结果
        MyInteger temp = *this;
        //后 递增
        m_Num++;
        //最后 将记录结果返回
        return temp;
    }

private:
    int m_Num;
};

//全局重载左移运算符<<
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();

    system("pause");
    return 0;
}
0
1
请按任意键继续. . .

上面写了前置和后置++,视频里要求自己重头写一遍--,来加深印象,下面是自己写的--

#include<iostream>
using namespace std;

class MyInteger
{
    //全局函数做友元, 访问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;
};

//重载左移运算符
//operator<<(cout, myint)本质是 cout<<myint
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();
    cout<<endl;
    test02();

    return 0;
}

🌳赋值运算符重载

C++编译器给一个类添加4个函数
1,默认(无参,函数体空)
2,析构(无参,函数体空)
3,拷贝(对属性值拷贝)
4,赋值运算符 operator=,对属性值拷贝

如果类中属性指向堆区,做赋值操作就会出现深浅拷贝问题

关于代码第36行的GPT解释

//深拷贝操作
m_Age = new int(*p.m_Age);

在 C++ 中,赋值运算符 = 的默认实现是浅拷贝。对于类中含有指针成员的情况,这就会产生问题。浅拷贝只是简单地将指针从源对象复制到目标对象,使得两个对象的指针成员指向同一块内存地址,也就是说,如果堆区中的数据被释放了,两个对象的数据都被释放了,就会产生异常。

因此,在定义类中含有指针成员的情况下,需要通过重载赋值运算符 = 实现深拷贝,即为目标对象开辟新的内存地址,把源对象中的数据拷贝进去。

具体来讲,你所提供的代码中,在重载的赋值运算符函数 operator= 中,首先判断 m_Age 指针是否为空,如果不为空,则释放该段内存,再通过 new int 重新开辟内存,将源对象的年龄数据拷贝到新的内存中,从而实现了深拷贝操作。

总之,深拷贝会分配一个新的内存块,并将源对象的信息复制到新的内存块中,两个对象之间没有任何关系。相反,浅拷贝只是复制指针,它们指向相同的内存块,而不是两块不同的内存。这就是为什么在类中含有指针成员时,需要明确指定拷贝构造函数和赋值运算符的实现方式,来避免指针之间的未知行为

#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) //传Person对象进来
    {
        //编译器提供浅拷贝
        //m_Age = p.m_Age;

        //先判断是否有属性在堆区 有的话先释放干净 再深拷贝
        if(m_Age != NULL) {
            delete m_Age;
            m_Age = NULL;
        }
        //深拷贝操作
        m_Age = new int(*p.m_Age);

        //返回对象本身
        return *this; //返回对象本题, *解引用, this是指针
        //返回自身, 实现连等的操作
    }

    int *m_Age; //m_Age指针去维护堆区数据
};

test01()
{
    Person p1(18);
    Person p2(20);
    Person p3(30);

    p3 = p2 = p1;

    p2 = p1; //赋值操作

    cout<<"p1年龄: "<<*p1.m_Age<<endl; //*解引用
    cout<<"p2年龄: "<<*p2.m_Age<<endl;
    cout<<"p3年龄: "<<*p3.m_Age<<endl;
}


int main()
{
    test01();

//    int a = 10, b = 20, c = 30;
//    c = b = a;
//    cout<<"a = "<<a<<" b = "<<b<<" c = "<<c<<endl;

    system("pause");
    return 0;
}

🌳关系运算符重载

关系运算符重载:让两个自定义类型对象进行对比操作

#include<iostream>
using namespace std;

//重载关系运算符
class Person
{
public:
    Person(string name, int age)
    {
        m_Name = name;
        m_Age = age;
    }
    //重载 == 号
    bool operator==(Person &p)
    {   //自身姓名 == 传入姓名, 自身年龄 == 传入年龄
        if(this->m_Name == p.m_Name && this->m_Age == p.m_Age)
            return true;
        return false;
    }

    bool operator!=(Person &p)
    {
        if(this->m_Name == p.m_Name && this->m_Age == p.m_Age)
            return false;
        return true;
    }

    string m_Name;
    int m_Age;

};

test01()
{
    Person p1("Jerry", 18);

    Person p2("Jerry", 18);

    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()
{
    test01();

    system("pause");
    return 0;
}
p1 == p2
p1 == p2
请按任意键继续. . .

🌳函数调用运算符重载

函数调用运算符()也可以重载
由于重载后使用方式非常像函数的调用,称为仿函数
仿函数没有固定写法,非常灵活

仿函数就是重载了函数调用运算符()的类

代码中MyPrint和MyAdd分别是打印输出类和加法类的仿函数,它们重载了函数调用运算符(),并可以像函数一样调用

#include<iostream>
using namespace std;

//函数调用运算符重载


//打印输出类
class MyPrint
{
public:

    //重载函数调用运算符
    void operator()(string test) //第一个()表示重载的运算符, 第二个()是形参列表
    {
        cout<<test<<endl;
    }

};

void MyPrint02(string test)
{
    cout<<test<<endl;
}

void test01()
{
    MyPrint myPrint;
    //使用起来非常像函数调用, 称之为仿函数
    myPrint("hello world"); //重载后的(), 让对象使用()

    MyPrint02("hello world"); //函数调用
}

//仿函数非常灵活, 没有固定写法
class MyAdd
{
public:

    int operator()(int num1, int num2)
    {
        return num1 + num2;
    }
};

void test02()
{
    MyAdd myadd; //有名myadd
    int ret = myadd(100, 120);

    cout<<"ret = "<<ret<<endl;
    //匿名函数对象
    cout<<MyAdd() (100, 130)<<endl;
    //MyAdd()创建了个匿名对象, 没有名, 重载了()
}

int main()
{
    //test01();
    test02();

    system("pause");
    return 0;
}
ret = 220
230
请按任意键继续. . .

🔑总结

跟着敲一遍,不懂就百度 + gpt,确实增加了对C++的理解,同时自己补充大量注释,辅助理解,,,每天2个视频,坚持3个月,就能看完了,真的好难

🌼返回对象 -- 链式调用

C++ Primer 第 7 章,Github代码中,有一个链式调用的经典例子,代码👇

#include<string>
#include<iostream>

class Screen {
public:
    // 定义类型别名
    using pos = std::string::size_type;

    // 构造函数
    Screen(pos height, pos width, char c) : height(height)
             , width(width), contents(height * width, c) {}

    // 成员函数声明
    inline Screen& move(pos r, pos c); // 光标移动到(r,c)
    inline Screen& set(char c); // 设置当前位置字符
    inline Screen& set(pos r, pos c, char ch); // 设置(r,c)字符
    const Screen& display(std::ostream& os) const; // 打印
    Screen& display(std::ostream& os); // 打印(非cosnt)

private:
    // 私有成员函数
    void do_display(std::ostream& os) const; // display() 的辅助函数

    // 成员变量
    pos cursor = 0; // 光标位置
    pos height = 0; // 屏幕高度
    pos width = 0; // 宽度
    std::string contents; // 内容,输出的是一行
};

// move 函数定义
inline Screen& Screen::move(pos r, pos c) {
    cursor = r * width + c; // 计算新的光标位置
    return *this; // 返回当前对象引用,以支持 链式调用
}

// set 函数定义(设置当前光标位置的字符)
inline Screen& Screen::set(char c) {
    // 因为 set() 是类内函数,只不过类外实现,
    // 当然可以调用私有成员 contentes 和 cursor
    contents[cursor] = c; // 当前光标位置字符为 c
    return *this; // 链式调用
}

// set 函数重载(指定位置)
inline Screen& Screen::set(pos r, pos c, char ch) {
    // 每次输出一行
    contents[r * width + c] = ch; // (r, c)字符为 c
    return *this; // 链式调用
}

// display() 函数 const 版本(输出流打印内容)
const Screen& Screen::display(std::ostream& os) const {
    do_display(os); // 私有辅助函数 do_display 打印
    return *this; // 返回对象引用 -- 链式调用
}

// display() 非 const 版本
Screen& Screen::display(std::ostream& os)
{
    do_display(os);
    return *this;
}

// do_display() 实际打印的函数
void Screen::do_display(std::ostream& os) const {
    os << contents; // 输出屏幕内容 到 给定输出流
}

int main()
{
    // 创建 Screen 对象
    Screen myScreen(5, 5, 'X');
    myScreen.move(4, 0).set('#').display(std::cout);
    std::cout << "\n";
    myScreen.display(std::cout);
    std::cout << "\n";

    return 0;
}
XXXXXXXXXXXXXXXXXXXX#XXXX
XXXXXXXXXXXXXXXXXXXX#XXXX
C++中的运算符重载可以通过函数来实现。函数是定义在类外部的普通函数,但是可以访问类的所有私有成员。通过将运算符重载函数声明为类的函数,可以使该函数访问类的私有成员。 下面是一个示例代码,演示了如何通过函数实现运算符重载: ```c++ #include <iostream> class Complex { public: Complex(double real = 0.0, double imag = 0.0) : real_(real), imag_(imag) {} double real() const { return real_; } double imag() const { return imag_; } private: double real_; double imag_; friend Complex operator+(const Complex& c1, const Complex& c2); }; Complex operator+(const Complex& c1, const Complex& c2) { return Complex(c1.real_ + c2.real_, c1.imag_ + c2.imag_); } int main() { Complex c1(1.0, 2.0); Complex c2(3.0, 4.0); Complex c3 = c1 + c2; std::cout << "real: " << c3.real() << ", imag: " << c3.imag() << std::endl; return 0; } ``` 在上面的代码中,我们定义了一个Complex类,包含了两个私有成员变量real_和imag_,表示复数的实部和虚部。我们通过函数operator+来实现运算符重载,使得两个Complex对象可以通过"+"运算符相加。在函数operator+中,我们可以访问Complex类的私有成员变量real_和imag_,从而实现了运算符重载。 在main函数中,我们创建了两个Complex对象c1和c2,并通过运算符重载将它们相加,最终得到一个新的Complex对象c3。我们可以通过调用c3的real()和imag()方法来获取它的实部和虚部。
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

千帐灯无此声

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值