2014-06-17 77 views
0

我是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) ; 
} 
+0

C++提示#1避免堆內存,使用stl類型。而不是'Car * fleet []'使用std :: vector ' –

+0

不使用多態數組。 – Rakib

+0

@ChrisDrew我不明白爲什麼這不可能是堆棧內存的任何理由? 'static int avg(Measurable * obj [],int num)'可以是'static int avg(const std :: vector &obj,int num)',並且輸出中不會有性能損失或差異。 –

回答

3

該錯誤消息是明確的,Car**Measurable**是不同類型的,而不是隱式轉換(雖然Car*可以轉換爲Measurable*) 。另外it is dangerous to use polymorphic array。這裏是一個解決方案,您可以嘗試:

template<class T> 
class Data { 

    public: 
    static double avg (vector<T>& obj) { 
     double size = 0 ; 
     for (int i = 0 ; i < obj.size() ;i++) 
     { 

      size += obj[i].getMeasurable() ; 
     } 
     return size/obj.size() ; 
     } 
}; 

int main() { 

     vector<Car> fleet; 
     fleet.push_back(Car(1)); 
     fleet.push_back(Car(2)); 
     fleet.push_back(Car(3)); 
     fleet.push_back(Car(4)); 

     double sum = Data<Car>::avg (fleet) ; 

     cout<<sum<<endl; 
    } 

如果你想創建其他類從Measurable繼承,並希望使用通用的方式方法,那麼你可以使用指針,但是你必須手動分配/取消分配這些。

class Data { 

public: 
static double avg (vector<Measurable*> obj) { 
    double size = 0 ; 
    for (int i = 0 ; i < obj.size() ;i++) 
    { 

     size += obj[i]->getMeasurable() ; 
    } 
    return size/obj.size() ; 
} 
}; 



int main() { 


vector<Measurable*> fleet; 
fleet.push_back(new Car(1)); 
fleet.push_back(new Car(2)); 
fleet.push_back(new Car(3)); 
fleet.push_back(new Car(4)); 

double sum = Data::avg (fleet) ; 

cout<<sum<<endl; 

for (int i=0;i<fleet.size();i++) 
{ 
    delete fleet[i]; 
} 

fleet.clear(); 
} 

請注意,基類析構函數應始終爲virtual

+0

謝謝。我想我在打電話時可以強制轉換。 – user2737926

+0

like double sum = Data :: avg((Measurable **)fleet,4);即使這似乎有幫助。 – user2737926

+0

@ user2737926,no。強制轉換會產生不正確的行爲。檢查回覆中的鏈接。 – Rakib