C++之运算符的重载初识

空类占一个字节!!!

1、友元机制

  1. 种类:
    1. 友元类
    2. 友元函数
    3. 友元成员函数
  2. 作用:提高程序的运行效率(让类的非公有函数可以直接访问类的非公有成员,省去了函数的调用过程)
  3. 缺点:破坏了C++的封装性
  4. 注意事项:
    1. 单向访问(只有friend才可以访问我的变量)
    2. 不可以传递
  5. 友元成员函数:声明另外一个类中的某一个成员函数可以访问本类(所有成员函数必须在类外声明)

2、函数运算符的重载

  • 类型转换运算符的重载

    • ++i

    • i++

      • i ++ 在实现的过程中会创建一个新的临时变量存储
      • ++ i 不会创建一个新的临时变量 
#include <iostream>
#include <string.h>
#include <string>

using namespace std;

using p_func = void(*)(void);

class Test
{
public:
    int m_num;
    string m_s;
    char *m_ptr;


    Test()
    {
        m_ptr = new char[100];
    }


    Test(int num, string s, char *ptr) : m_num(num), m_s(s)
    {
        int len = strlen(ptr);
        this->m_ptr = new char[len + 1];
        strcpy(m_ptr, ptr);
    }

    ~Test()
    {
        delete[] m_ptr;
    }

    static void print()
    {
        cout << "hello world" << endl;
    }

    Test &operator=(const Test &other)
    {
        if (this != &other)
        {
            this->m_num = other.m_num;
            this->m_s = other.m_s;
            int len = strlen(other.m_ptr);
            this->m_ptr = new char[len + 1];
            strcpy(m_ptr, other.m_ptr);
        }

        return *this;
    }

    bool operator>(const Test &t)
    {
        return this->m_num > t.m_num;
    }
    
    bool operator<(const Test &t)
    {
        return this->m_num < t.m_num;
    }

    friend ostream &operator<<(ostream &out, const Test &t)
    {
        out << "num = " << t.m_num << endl;
        out << "s = " << t.m_s << endl;
        out << "ptr = " << t.m_ptr;

        return out;
    }

    friend istream &operator>>(istream &in, Test &t)
    {
        in >> t.m_num;
        in >> t.m_s;
        in >> t.m_ptr;

        return in;
    }
   
    operator int()    //类型转换运算符的重载
    {
        return this->m_num;
    }

    operator char*()   //类型转换运算符的重载
    {
        return this->m_ptr;
    }

    operator p_func()   //类型转换运算符的重载
    {
        return print;
    }

    //i++ ,++i;  //实现
    //()函数运算符 --  函数对象
};

int main()
{
    string s = "hello world";
    Test t1(1, s, "zhangsan");
    Test t2;
    t2.operator=(t1);

    //cout << s << "hello" << endl;
    //cout.operator<<(cout,t2);
    //operator<<(cout,t2);
    cout << t2 << "hello" << endl;

    Test t3;
    cin >> t3;

    cout << t3 << endl;

    if(t2 > t3)
    {
        cout << "t2 > t3" << endl;
    }

    int num = static_cast<int>(t3);
    int num2 = static_cast<int>(t2);
    cout << num << endl;
    cout << num2 << endl;

    string s2 = static_cast<string>(t3);
    char *ptr = static_cast<char *>(t2);
    //cout << s2 << endl;
    cout << ptr << endl;

    p_func f = static_cast<p_func>(t2);

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值