说明
继续上面的内容
要求:
- 按照数组下标由小到大,数组下标运算符按照次序分别返回圆心x坐标,圆心y坐标,圆的半径。
- 下标超出范围,则返回带符号整型数中最小的值
- 可以为MyCircle类添加数据域成员并且修改其函数成员。
注意以下几个要点:
- 因为要重载方括号运算符,所以应该返回函数的引用
-
int
的最小值获取方法:numeric_limits<int>::min();
需要引用<limits>
库
代码
#include <iostream>
#include <string>
#include <sstream>
#include <limits>
using namespace std;
class MyShape {
protected:
int R_, G_, B_;
string colorToString() {
stringstream ss;
ss << R_ << " " << G_ << " " << B_;
return ss.str();
}
public:
void setColor(int R, int G, int B) {
R_ = R; G_ = G, B_ = B;
}
int getR() {
return R_;
}
int getG() {
return G_;
}
int getB() {
return B_;
}
virtual void Draw() = 0;
MyShape() {
R_ = 255; G_ = 255, B_ = 255;
}
};
class MyCircle : public MyShape {
private:
int x_, y_, radius_;
int max_int;
public:
MyCircle(int x, int y, int radius) {
x_ = x;
y_ = y;
radius_ = radius;
max_int = numeric_limits<int>::min();
}
MyCircle() {
x_ = y_ = 200;
radius_ = 100;
max_int = numeric_limits<int>::min();
}
MyCircle(MyCircle& aCircle) {
x_ = aCircle.x_;
y_ = aCircle.y_;
radius_ = aCircle.radius_;
R_ = aCircle.getR();
G_ = aCircle.getG();
B_ = aCircle.getB();
max_int = numeric_limits<int>::min();
}
void setCenter(int x, int y) {
x_ = x;
y_ = y;
}
void setRadius(int radius) {
radius_ = radius;
}
void Draw() {
}
bool operator > (const MyCircle c2) const;
bool operator < (const MyCircle c2) const;
bool operator >=(const MyCircle c2)const;
bool operator <=(const MyCircle c2)const;
bool operator ==(const MyCircle c2)const;
bool operator !=(const MyCircle c2)const;
int& operator [] (int n);
//----在此处添加关系运算符 >、<、>=、<=、==、!= 的重载原型声明
};
bool MyCircle::operator<(const MyCircle c2)const {
return radius_ < c2.radius_;
}
bool MyCircle::operator>(const MyCircle c2)const {
return radius_ > c2.radius_;
}
bool MyCircle::operator>=(const MyCircle c2)const {
return radius_ >= c2.radius_;
}
bool MyCircle::operator<=(const MyCircle c2)const {
return radius_ <= c2.radius_;
}
bool MyCircle::operator==(const MyCircle c2)const {
return radius_ == c2.radius_;
}
bool MyCircle::operator!=(const MyCircle c2)const {
return radius_ != c2.radius_;
}
int& MyCircle::operator[](int n) {
if (n>2||n<0)
{
return max_int;
}
else
{
switch (n)
{
case 0:return x_;
case 1:return y_;
case 2:return radius_;
}
}
}
//----在此处添加关系运算符的重载定义
int main() {
int x, y, r = 0;
cin >> x >> y >> r;
MyCircle c1(x, y, r);
MyCircle c2;
c2[2] = x;
for (int i = 0; i <= 3; i++) {
cout << c1[i] << endl;
cout << c2[i - 1] << endl;
}
return 0;
}
网友评论