我是C++新手。我正在學習C++中的繼承。我無法理解編譯時錯誤。 我有超級可測量和汽車和國家從可衡量派生。在可衡量我有 純虛函數getMeasurable被子類覆蓋。我有Data類,其中 迭代通過可測量對象(汽車或國家)並計算平均值。C++錯誤:繼承無效轉換
我打錯誤
measure.cc: In function ‘int main()’:
measure.cc:70: error: invalid conversion from ‘Car**’ to ‘Measurable**’
measure.cc:70: error: initializing argument 1 of ‘static int Data::avg(Measurable**, int)’
代碼
#include <iostream>
class Measurable ;
class Measurable {
public:
virtual int getMeasurable() = 0 ;
};
class Country: public Measurable {
private:
int size ;
public:
Country(int size): size(size) {
}
int getMeasurable() {
return size ;
}
};
class Car: public Measurable {
private:
int mileage ;
public:
Car(int size): mileage(size) {
}
int getMeasurable() {
return mileage ;
}
};
class Data {
public:
static int avg (Measurable* obj[] , int num) {
double size = 0 ;
for (int i = 0 ; i < num ;i++)
{
size += obj[i]->getMeasurable() ;
}
return size/num ;
}
};
int main() {
Car* fleet[] = {
new Car (1) , new Car (2) , new Car (3) , new Car (4)
};
double sum = Data::avg (fleet ,4) ;
}
C++提示#1避免堆內存,使用stl類型。而不是'Car * fleet []'使用std :: vector' –
不使用多態數組。 – Rakib
@ChrisDrew我不明白爲什麼這不可能是堆棧內存的任何理由? 'static int avg(Measurable * obj [],int num)'可以是'static int avg(const std :: vector&obj,int num)',並且輸出中不會有性能損失或差異。 –