2012-04-15 94 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创建对象。