0
Q
C++超載
A
回答
6
您不需要重載這些,因爲std::string
已經提供了它們。
一般情況下,超載的功能,你不調用類。你不能叫一個班。您也可以不向類中添加方法。如果你想提供,例如,operator <
對現有類A
,你必須創建是在A
的命名空間的免費功能:大於
bool operator<(const A& left, const B& right) {
// implement logic here
}
0
二元運算符(>)和小於( <)運算符主要用於if語句,因此下面的源代碼示例也使用if語句。讓我們來看看操作符重載源代碼:
#include<iostream>
using namespace std;
class Box {
public:
Box(double boxLength, double boxWidth, double boxHeight)
:length(boxLength), width(boxWidth), height(boxHeight) {}
// Compute the volume of a box.
double volume() const {
return length*width*height;
}
// First inline function
inline bool operator<(const Box& someBox) const {
return volume() < someBox.volume();
}
// Second inline function
inline bool operator<(const double someValue) const {
return volume() < someValue;
}
// Third inline function
inline bool operator>(const Box& someBox) const {
return volume() > someBox.volume();
}
// Fourth inline function
inline bool operator>(const double someValue) const {
return volume() > someValue;
}
private:
double length;
double width;
double height;
};
int main() {
Box myBox(15.0, 10.0, 5.0);
Box myBox2(15.0, 5.0, 5.0);
cout << "The myBox volume is: " << myBox.volume() << "\n";
cout << "The myBox2 volume is: " << myBox2.volume() << "\n";
// Trying the less than binary operator
if(myBox < myBox2) {
cout << "The myBox volume is less than myBox2 volume!\n";
}else{
cout << "The myBox volume is not less than myBox2 volume!\n";
}
// Trying the less than binary operator
if(myBox < 1000) {
cout << "The myBox volume is less than 1000!\n";
}else{
cout << "The myBox volume is not less than 1000!\n";
}
// Trying the greater than binary operator
if(myBox > myBox2) {
cout << "The myBox volume is greater than myBox2 volume!\n";
}else{
cout << "The myBox volume is not greater than myBox2 volume!\n";
}
// Trying the greater than binary operator
if(myBox > 500) {
cout << "The myBox volume is greater than 500!\n";
}else{
cout << "The myBox volume is not greater than 500!\n";
}
return 0;
}
你可以從字符串繼承箱重載這些運營商的字符串
相關問題
- 1. C++:超載=當==重載
- 2. C函數超載
- 3. C#參數+超載
- 4. C#超載問題
- 5. C++動態超載
- 6. C++從<<超載
- 7. C++超載<<再次
- 8. 運算符*超載C++
- 9. C++「超載」的if()語句
- 10. 運算符+超載C++
- 11. C++二叉樹超載
- 12. C#:下載超時的URL
- 13. C++運行超載,碰撞
- 14. 僅輸出超載C++
- 15. C#語法糖超載
- 16. C++超載運算符[]
- 17. 寫C++操作符超載?
- 18. C++超載運算符
- 19. C++繼承超載成員
- 20. 關於C++中的超載
- 21. C++超載[]操作不
- 22. 方法c沒有超載#
- 23. 未能超載運算符<<(C++)
- 24. C++ 11 <<運算符specefic超載
- 25. C++運算符超載衝突
- 26. C++曖昧的操作模板超載
- 27. C++錯誤typedef不能超載
- 28. 需要一些超載信息C#
- 29. C++的朋友操作符+超載
- 30. C++/cli代表+ lambda +超載函數