C++ 运算符重载:
您可以重定义或重载大部分 C++ 内置的运算符。这样,您就能使用自定义类型的运算符。
重载的运算符是带有特殊名称的函数,函数名是由关键字 operator 和其后要重载的运算符符号构成的。
与其他函数一样,重载运算符有一个返回类型和一个参数列表。重载 + 运算符 , 把两个 Box 相加
Box operator+(const Box b)
demo:
h = this->length - b.length;
box_.width = this->width - b.width;
box_.height = this->height - b.height;
return box_;
}
private:
double length;
double width;
double height;
};
int main()
{
Box a;
a.setHeight(5);
a.setWidth(5);
a.setLength(2);
std::cout << "a. volume:" << a.getVolume() << std::endl;
Box b;
b.setHeight(5);
b.setWidth(5);
b.setLength(5);
std::cout << "b. volume:" << b.getVolume() << std::endl;
Box c;
c = a + b;
std::cout << "c. volume:" << c.getVolume() << std::endl;
Box d;
d = b - a;
std::cout << "d. volume:" << d.getVolume() << std::endl;
system("pause");
return 0;
}