学习C++笔记297

简介: C++ 重载运算符和重载函数

下面的实例使用成员函数演示了运算符重载的概念。在这里,对象作为参数进行传递,对象的属性使用 this 运算符进行访问,如下所示:

实例

#include<iostream>usingnamespacestd;  classBox{   public:         doublegetVolume(void)      {         returnlength * breadth * height;       }      voidsetLength(doublelen)      {          length = len;       }        voidsetBreadth(doublebre)      {          breadth = bre;       }        voidsetHeight(doublehei)      {          height = hei;       }      // 重载 + 运算符,用于把两个 Box 对象相加      Boxoperator+(constBox& b)      {         Boxbox;          box.length = this->length + b.length;          box.breadth = this->breadth + b.breadth;          box.height = this->height + b.height;          returnbox;       }   private:       doublelength;      // 长度      doublebreadth;     // 宽度      doubleheight;      // 高度};// 程序的主函数intmain(){   BoxBox1;                // 声明 Box1,类型为 Box   BoxBox2;                // 声明 Box2,类型为 Box   BoxBox3;                // 声明 Box3,类型为 Box   doublevolume = 0.0;     // 把体积存储在该变量中     // Box1 详述   Box1.setLength(6.0);     Box1.setBreadth(7.0);     Box1.setHeight(5.0);      // Box2 详述   Box2.setLength(12.0);     Box2.setBreadth(13.0);     Box2.setHeight(10.0);      // Box1 的体积   volume = Box1.getVolume();    cout << "Volume of Box1 : " << volume <<endl;      // Box2 的体积   volume = Box2.getVolume();    cout << "Volume of Box2 : " << volume <<endl;      // 把两个对象相加,得到 Box3   Box3 = Box1 + Box2;      // Box3 的体积   volume = Box3.getVolume();    cout << "Volume of Box3 : " << volume <<endl;      return0;}

当上面的代码被编译和执行时,它会产生下列结果:

Volume of Box1:210

Volume of Box2:1560

Volume of Box3:5400

目录
相关文章
|
13小时前
|
存储 程序员 编译器
|
13小时前
|
存储 编译器 文件存储
|
8天前
|
存储 编译器 程序员
C++语言基础学习
C++语言基础学习
|
8天前
|
安全 API C++
逆向学习Windows篇:C++中多线程的使用和回调函数的实现
逆向学习Windows篇:C++中多线程的使用和回调函数的实现
10 0
|
8天前
|
C++ UED 开发者
逆向学习 MFC 篇:视图分割和在 C++ 的 Windows 窗口程序中添加图标的方法
逆向学习 MFC 篇:视图分割和在 C++ 的 Windows 窗口程序中添加图标的方法
9 0
|
13天前
|
设计模式 算法 程序员
【C++】大气、正规的编程习惯:C++学习路径与注意事项
【C++】大气、正规的编程习惯:C++学习路径与注意事项
14 0
|
18天前
|
存储 编译器 程序员
【C++高阶】C++继承学习手册:全面解析继承的各个方面
【C++高阶】C++继承学习手册:全面解析继承的各个方面
18 1
|
1天前
|
编译器 C语言 C++
|
1天前
|
编译器 C++
【C++】详解初始化列表,隐式类型转化,类静态成员,友元
【C++】详解初始化列表,隐式类型转化,类静态成员,友元
|
4天前
|
存储 编译器 C++
【C++】类和对象④(再谈构造函数:初始化列表,隐式类型转换,缺省值
C++中的隐式类型转换在变量赋值和函数调用中常见,如`double`转`int`。取引用时,须用`const`以防修改临时变量,如`const int& b = a;`。类可以有隐式单参构造,使`A aa2 = 1;`合法,但`explicit`关键字可阻止这种转换。C++11起,成员变量可设默认值,如`int _b1 = 1;`。博客探讨构造函数、初始化列表及编译器优化,关注更多C++特性。