[英]Template function ignores members from inherited class
我正在嘗試編寫一個程序來比較一些形狀的面積,形狀是基礎 class。 該程序還有 2 個從 Shape class 派生的其他類。
這就是我定義它們的方式:
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;
我想構建一個 function 接受任何 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;
}
我主要嘗試調用 function:
maxim<Shape>({*f3, *f4, *f5, *f6}).printMe();
該程序沒有任何錯誤,只顯示一個空字符串(由於maxx
是一個用空字符串初始化的Shape
)。
當我調用printMe()
方法時,對象f3
、 f4
、 f5
和f6
會正確顯示,所以我認為當我調用maxim
function 時,只有成員color
分配給對象。 沒有分配給它們的x
、 y
、 side
或radius
成員。
我認為問題在於對象只是Shapes
,它們只有color
成員。 有什么方法可以將列表中的對象解釋為 Cricles 和 Squares,以便我可以使用Area()
方法比較它們?
您正在嘗試在這里使用多態性。 不幸的是,C++ 中的多態性適用於指針或引用,但由於切片而不適用於普通對象(感謝 @Jarod42 的引用)。
並且由於無法將引用分配給(而是分配給 ref-ed 對象),因此您不能在容器或初始化列表中使用它們。
這意味着您將不得不在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();
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.