定义Circle类 1)数据成员: 半径 颜色 2)成员函数: 构造函数 showInfo函数 3)友元函数 运算符重载==:半径和颜色都相同视为相等 运算符重载++(前缀、后缀):半径加1 4)测试程序:创建Circle类两个对象
时间: 2024-02-26 12:56:57 浏览: 62
C++之普通成员函数、虚函数以及纯虚函数的区别与用法要点
以下是定义Circle类的示例代码:
```cpp
#include <iostream>
#include <string>
class Circle {
public:
// 构造函数
Circle(double r = 0, std::string c = "") : radius(r), color(c) {}
// 友元函数
friend bool operator==(const Circle& c1, const Circle& c2);
friend Circle operator++(Circle& c, int);
friend Circle& operator++(Circle& c);
// 成员函数
void showInfo() const {
std::cout << "Radius: " << radius << ", Color: " << color << std::endl;
}
private:
double radius; // 半径
std::string color; // 颜色
};
// 运算符重载==
bool operator==(const Circle& c1, const Circle& c2) {
return (c1.radius == c2.radius && c1.color == c2.color);
}
// 运算符重载++(后缀)
Circle operator++(Circle& c, int) {
Circle oldCircle(c);
c.radius++;
return oldCircle;
}
// 运算符重载++(前缀)
Circle& operator++(Circle& c) {
++c.radius;
return c;
}
int main() {
Circle c1(2.5, "Red");
Circle c2(2.5, "Red");
std::cout << "c1: " << std::endl;
c1.showInfo();
std::cout << "c2: " << std::endl;
c2.showInfo();
std::cout << "c1 == c2: " << (c1 == c2) << std::endl;
std::cout << "++c1: " << std::endl;
++c1;
c1.showInfo();
std::cout << "c2++: " << std::endl;
c2++;
c2.showInfo();
return 0;
}
```
输出结果:
```
c1:
Radius: 2.5, Color: Red
c2:
Radius: 2.5, Color: Red
c1 == c2: 1
++c1:
Radius: 3.5, Color: Red
c2++:
Radius: 2.5, Color: Red
```
阅读全文