2011-06-03 25 views

回答

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; 
} 

你可以從字符串繼承箱重載這些運營商的字符串