我正在嘗試撰寫一個程式,按區域比較一些 Shape,Shape 是基類。該程式還有兩個派生自 Shape 類的其他類。
我是這樣定義它們的:
class Shape
{
protected:
string color;
public:
Shape();
Shape(string);
virtual double Perimeter();
virtual void printMe();
virtual double Area();
};
class Square:
public Shape
{
int x, y;
double side;
public:
Square();
Square(string, int, int, double);
double Perimeter();
void printMe();
double Area();
};
class Circle:
public Shape
{
int x, y, radius;
public:
Circle();
Circle(string, int, int, int);
double Perimeter();
void printMe();
double Area();
};
在主要,我創建了以下物件:
Shape f1, f2("green");
Circle c1, c2("green", 2, 2, 2);
Square p1, p2("blue", 0, 0, 5);
Shape* f3 = &c1;
Shape* f4 = &c2;
Shape* f5 = new Square("blue", 1, 0, 2);
Shape* f6 = &p2;
我想構建一個函式,它接受任何 Shape 物件并回傳具有最大面積的物件。我試過這樣:
template <typename T>
T maxim(initializer_list<T> list) {
T maxx;
for (auto i : list)
{
if (i.Area() > maxx.Area())
maxx = i;
}
return maxx;
}
在 main 中,我嘗試呼叫該函式:
maxim<Shape>({*f3, *f4, *f5, *f6}).printMe();
該程式沒有任何錯誤,只顯示一個空字串(由于這樣的事實,maxx就是一個Shape是與一個空字串初始化)。
The objects f3,f4,f5 and f6 are displayed right when I call the printMe() method, so I figured that when I call the maxim function, only the member color is assigned to the objects. There is no x,y,side or radius member assigned to them.
I think the problem is that the objects are just Shapes and they only have the color member.
Is there any way the objects in the list can be interpreted as Cricles and Squares so I can compare them using Area() method?
uj5u.com熱心網友回復:
您正在嘗試在這里使用多型性。不幸的是,C 中的多型性適用于指標或參考,但由于切片而不適用于普通物件(感謝@Jarod42 提供該參考)。
并且由于無法將參考分配給(而是分配給被參考的物件),因此您不能在容器或初始化串列中使用它們。
這意味著您將不得不在 中使用良好的舊指標maxim:
template <typename T>
T* maxim(initializer_list<T*> list) {
T* maxx = nullptr;
for (auto i : list)
{
if (nullptr == maxx || i->Area() > maxx->Area())
maxx = i;
}
return maxx;
}
從那時起,您將能夠:
maxim<Shape>({f3, f4, f5, f6})->printMe();
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/385763.html
標籤:c oop polymorphism
