2013-05-01 48 views
0

我遇到了一个小程序的问题。我希望你能睁开我的眼睛。C++中的动态链接不起作用

我有一类,“用户”,用“名称”作为一类部件和一个“的toString()”方法:

class User 
{ 
protected: 
     string name; 
public: 
     User(){} 
     User(string name) { this->name = name; } 
     virtual string toString() const { return name; } 
}; 

我有另一个类,“雇员”延伸用户,和它也包括一个“id”和过载“的toString()”方法:

class Employee : public User 
{ 
private: 
     string id; 
public: 
     Employee(string name, string id) : User(name) { this->id = id;} 
     string toString() const { return "("+id+")"+name; } 
}; 

那么,现在我有另一个类,“栈”与用户的阵列(用户对象,而不是用户指针):

class Stack 
{ 
private: 
     User *stack; 
     int sp; 
     int size; 
public: 
     Stack(int size){this->size = size; stack = new User[size]; sp = 0;} 

. 
. 
. 

问题是这样的:

Stack s(10); 
Employee e1("pepito", "1234"); 

cout << e1.toString(); // PRINTS (1234)pepito -> ITS OK 

s.push(e1); 
cout << s.pop().toString(); // PRINTS pepito -> WRONG (it uses the toString method of the super class). 

我想,我可以得到,因为这样的结果:

  • 存储对象而不是指针或引用的对象。
  • 在该行:stack = new User [size]中,它调用User的默认构造函数(我必须明确写入,并且我不知道这是否正确)。
+0

您的代码缺少Stack :: push和Stack :: pop函数。我认为错误在于这些功能。 – typ1232 2013-05-01 22:08:11

回答

1

我想,我可以得到,因为这样的结果:

  • 存储对象而不是指针或引用的对象。

正确。您正在动态分配一组User s。此阵列中的对象只能是User,而不是其他任何东西。他们从来没有Employee s。要在C++中获得多态行为,您需要使用指针或对User的引用。

+0

谢谢,它现在正在工作 – Pablo 2013-05-01 22:23:16