我对编程非常陌生,接近这个程序的结尾,但不能完全完成我一直坚持的最后一个细节。我试图切换指向* sp的形状指针,在我看来,我所做的工作应该是正确的,因为矩形和圆都是形状;但是,当我编译时,只有颜色的值发生变化。圆的区域打印而不是矩形的区域和周边打印0.任何帮助将不胜感激!更改指针指向的内容?
#include <iostream>
#include <string>
using namespace std;
double const pi = 3.1519;
class shape {
public:
shape() {};
shape(string);
virtual double getCircumference() {
return 0;
};
virtual double getPerimeter() {
return 0;
};
virtual double getArea() {
return 0;
};
string getColor();
protected:
string color;
};
string shape::getColor() {
return color;
}
class circle : public shape {
public:
circle(double r, string c) {
radius = r;
color = c;
};
double getArea();
double getCircumference();
private:
double radius;
};
double circle::getCircumference() {
return pi * radius * 2;
}
double circle::getArea() {
return pi * radius * radius;
}
class rectangle:public shape {
public:
rectangle(double w, double l, string c) {
width = w;
length = l;
color = c;
};
double getArea();
double getPerimeter();
private:
double length;
double width;
};
double rectangle::getPerimeter() {
return width * 2 + length * 2;
}
double rectangle::getArea() {
return length * width;
}
void change(shape *sp, shape *sp1) {
*sp = *sp1;
}
int main() {
circle mary(3.2, "Green");
shape *sp = new circle(4.5, "Yellow");
cout << "Circle #1 is " << mary.getColor() << endl;
cout << "Circle #1 has an area of " << mary.getArea() << endl;
cout << "Circle #1 has a circumference of " << mary.getCircumference() << endl << endl;
cout << "Circle #2 is " << sp->getColor() << endl;
cout << "Circle #2 has an area of " << sp->getArea() << endl;
cout << "Circle #2 has a circumference of " << sp->getCircumference() << endl << endl;
shape *sp1 = new rectangle(1.0, 2.1, "Red");
change(sp, sp1);
cout << "Rectangle #1 is " << sp->getColor() << endl;
cout << "Rectangle #1 has an area of " << sp->getArea() << endl;
cout << "Rectangle #1 has a perimeter of " << sp->getPerimeter() <<endl<< endl;
}
你忘了在'void change(shape * sp,shape * sp1)'中通过引用传递。应该是'void change(shape *&sp,shape *&sp1)' – NathanOliver
Thanks NathanOliver! – Reggie78
作为一个函数,我不确定'change'的含义(除了帮助你学会通过引用来改变?),当你可以只是'sp = new rectangle ...'而不是? (无论哪种方式,你都不会通过删除旧对象来泄漏内存)。 – crashmstr