C++ overloading [duplicate]
Possible Duplicate:
Operator overloading
I would like to overload < and > to alphabetize strings and I'm not sure how to do it.
How do I call the string c开发者_运维问答lass again to redefine < and >?
You don't need to overload these, as std::string
already provides them.
In general, to overload functions, you don't call a class. You cannot call a class. You can also not add methods to classes. If you want to provide, for instance, operator <
for an existing class A
, you have to create is as a free function in the namespace of A
:
bool operator<(const A& left, const B& right) {
// implement logic here
}
The binary operators greater than (>) and less than (<) operators are mostly used in if statements, so the source code example below is also using if statements. Let's look at the operator overloading source code:
#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;
}
you can inherit Box from String to overload these operators for string
精彩评论