2012-04-15 107 views
2

我正在編寫代碼以存儲不同程度的考試結果(物理學&化學當前)。std ::基類指針映射

我有一個抽象基類student這是如下:

class student{ 
public: 
    virtual ~student(){} 
    //virtual function to add course + mark 
    virtual void addresult(std::string cName,int cCode,double cMark)=0; 
    //virtual function to print data 
    virtual void printinfo()=0;  //to screen 
    virtual void outputinfo(std::string outputfilename)=0;  //to file 
}; 

然後我有物理派生類(和將具有類似一個用於化學):

class physics : public student{ 
protected: 
    std::string studentname; 
    int studentID; 
    std::map<int,course> courses; //map to store course marks 
public: 
    //constructors/destructors 
    void addresult(std::string cName,int cCode,double cMark){course temp(cName,cCode,cMark);courses[cCode]= temp;} 

    void printinfo(){ 
     //function to output information to screen  
    } 

    void outputinfo(std::string outputfilename){ 
     //function to write student profile to file 
    } 
};  

在我的主體,然後我想有一張地圖,可以存儲所有的學生(物理和化學)。學生ID是指向物理或化學的基類指針的鍵。學生是,我猜測,要走的路。

我嘗試下面的代碼:

map<int,student*> allstudents; 
physics S1(sName,sID); 
physics* S2 = &S1; 
allstudents.insert(pair<int,student*>(sID,S2)); 

但這並沒有工作。我想我對於什麼應該指向什麼有些困惑。你甚至可以用地圖做這個嗎? 如果我存儲信息,是否還需要「清理」。這條路? 感謝您的幫助。

+3

公共繼承模仿IS-A關係,但物理學是科學而不是學生。 – sbi 2012-04-15 10:05:24

回答

3

如果您使用的指針超過一秒鐘,則不應在堆棧上創建對象,然後指向它!一旦下一個}出現,它就會消失,你的指針將會失效!

改爲使用physics* S2 = new physics(sName, sID);。在地圖上的所有指針上使用delete(迭代器在這裏很方便)清理!

+1

或使用[智能指針](http://stackoverflow.com/questions/106508/what-is-a-smart-pointer-and-when-should-i-use-one),所以你沒有任何頭痛從手動內存管理和異常不安全... – 2012-04-15 10:11:08

+0

我已經改變爲: physics * S1 = new physics(sName,sID); allstudents.insert(pair (sID,S1)); 但仍然得到錯誤: 「c:\ program files \ microsoft visual studio 10.0 \ vc \ include \ utility(163):error C2440:'initializing':can not convert from'physics'to'student *'」 任何想法? – QuantumO 2012-04-15 12:50:14

+0

看起來你錯過了*的某處。如果您沒有發現錯誤,請提出一個新問題。 – ypnos 2012-04-16 11:35:02

3

可以,但你錯過了幾件事情:

  • 你不尊重3的規則。您還需要在類中定義賦值運算符和複製構造函數。

  • 你可能遇到內存損壞問題:

以下時S1超出範圍

physics S1(sName,sID); 
physics* S2 = &S1; 
allstudents.insert(pair<int,student*>(sID,S2)); 

將插入變得晃來晃去的指針。您應該使用智能指針或將內存管理委託給地圖 - 即在地圖超出範圍時使用newdelete創建對象。