小工具知识网

当前位置: 首页 > 行业知识 > C++六个默认成员函数(下)

行业知识

C++六个默认成员函数(下)

2026-11-11 07:07:26 来源:互联网转载

目录

  • 1.运算符重载介绍
    • 重载流插入和流输出
    • 关于更多的重载
    • 2.赋值运算符重载
      • 关于返回值
        • 拷贝构造和赋值重载的一个区别
        • 3.const成员函数
          • 概念
            • 讨论
            • 问题:
            • 取地址及const取地址操作符重载
            • 结尾

              1.运算符重载介绍

              1.C++为了增强代码的可读性引入了运算符重载,运算符重载是具有特殊函数名的函数,也具有其返回值类型,函数名字以及参数列表,其返回值类型与参数列表与普通的函数类似。

              2.函数名字为: 关键字operator后面接需要重载的运算符符号

              3.函数原型: 返回值类型 operator操作符(参数列表)

              如:bool operator//友元函数声明 可以访问内部成员friend ostream& operatorout in d._year d._month d._day;return in;}public : Date(int year = 1900, int month = 1, int day = 1) { _year = year; _month = month; _day = day;} Date (const Date& d) { _year = d._year; _month = d._month; _day = d._day;} //支持连续赋值 Date& operator=(const Date& d) { //检测是否自己给自己赋值 if(this != &d) { _year = d._year; _month = d._month; _day = d._day;} return *this; }private:int _year ;int _month ;int _day ;} if(this != &d) { _year = d._year; _month = d._month; _day = d._day;}//注意这里的this是开辟在栈上的//是main函数创建的类中的 所以可以传引用返回 return *this; }Date d;return d;}static Date d;return d;} if (&left != &right) { left._year = right._year; left._month = right._month; left._day = right._day;} return left;}public: //取地址&重载Date* operator&(){return this;} //const取地址&重载const Date* operator&()const{return this;}private:int _year;int _month;int _day;};

上一篇:线性方程解析,基础概念、应用重点及实战解析

下一篇:网站图标怎么制作?