C++基础知识 - 成员函数重载运算符
2022/2/21 17:29:11
本文主要是介绍C++基础知识 - 成员函数重载运算符,对大家解决编程问题具有一定的参考价值,需要的程序猿们随着小编来一起学习吧!
运算符重载
-
为什么要使用运算符重载
-C/C++的运算符,支持的数据类型,仅限于基本数据类型。 -
问题:一头牛+一头马 = ?(牛马神兽?)
一个圆 +一个圆 = ? (想要变成一个更大的圆)
一头牛 – 一只羊 = ? (想要变成4只羊,原始的以物易物:1头牛价值5只羊) -
解决方案:
使用运算符重载
使用成员函数重载运算符
- 需求:把牛肉换猪肉, 羊肉换猪肉
规则:
一斤牛肉:2斤猪肉
一斤羊肉:3斤猪肉
Cow类
> Cow.h #pragma once class Pork; class Sheep; class Cow{ //牛类 public: Cow(int weight = 0); //使用运算符重载, 实现 牛肉 + 牛肉 = 猪肉 Pork operator+(const Cow& cow); //使用运算符重载, 实现 牛肉 + 羊肉 = 猪肉 Pork operator+(const Sheep& sheep); private: int weight; //重量 }; _________________________________________________________________________________________________________________________________ > Cow.cpp #include "Cow.h" #include "Pork.h" #include "Sheep.h" Cow::Cow(int weight){ this->weight = weight; } //一斤牛肉换两斤猪肉 Pork Cow::operator+(const Cow& cow){ return Pork((this->weight + cow.weight) * 2); } //一斤牛肉换两斤猪肉, 一斤羊肉换三斤猪肉 Pork Cow::operator+(const Sheep& sheep){ int tmp = (this->weight * 2) + (sheep.getWeight() * 3); return Pork(tmp); }
Sheep类
> Sheep.h #pragma once //羊类 class Sheep{ public: Sheep(int weight = 0); int getWeight() const; private: int weight; //重量 }; _________________________________________________________________________________________________________________________________ > Sheep.cpp #include "Sheep.h" Sheep::Sheep(int weight){ this->weight = weight; } int Sheep::getWeight() const{ return weight; }
Pork类
> Pork.h #pragma once #include <string> using namespace std; class Pork{ //猪肉类 public: Pork(int weight = 0); string description() const; private: int weight; }; _________________________________________________________________________________________________________________________________ > Pork.cpp #include <sstream> #include "Pork.h" Pork::Pork(int weight){ this->weight = weight; } string Pork::description() const{ stringstream ret; ret << this->weight << "斤"; return ret.str(); }
main.cpp
#include <iostream> #include <Windows.h> #include "Cow.h" #include "Pork.h" #include "Sheep.h" using namespace std; int main(void) { Pork p1; Cow c1(100); Cow c2(200); Sheep s1(100); //调用运算符重载 Pork operator+(const Cow& cow); p1 = c1 + c2; cout << "牛 + 牛 = 猪肉:" << p1.description() << endl; //调用运算符重载 Pork operator+(const Sheep& c1); p1 = c1 + s1; cout << "牛 + 羊 = 猪肉:" << p1.description() << endl; //羊+牛会报错, 因为没有定义对应的羊+牛运算符重载 //p1 = s1 + c1; system("pause"); return 0; }
这篇关于C++基础知识 - 成员函数重载运算符的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!
- 2024-05-15PingCAP 黄东旭参与 CCF 秀湖会议,共探开源教育未来
- 2024-05-13PingCAP 戴涛:构建面向未来的金融核心系统
- 2024-05-09flutter3.x_macos桌面os实战
- 2024-05-09Rust中的并发性:Sync 和 Send Traits
- 2024-05-08使用Ollama和OpenWebUI在CPU上玩转Meta Llama3-8B
- 2024-05-08完工标准(DoD)与验收条件(AC)究竟有什么不同?
- 2024-05-084万 star 的 NocoDB 在 sealos 上一键起,轻松把数据库编程智能表格
- 2024-05-08Mac 版Stable Diffusion WebUI的安装
- 2024-05-08解锁CodeGeeX智能问答中3项独有的隐藏技能
- 2024-05-08RAG算法优化+新增代码仓库支持,CodeGeeX的@repo功能效果提升