c++ - C++ 中的动态链接不起作用

标签 c++ inheritance dynamic linker overriding

我有一个小程序的问题。希望你能开开我的眼界。

我有一个类“User”,其中“name”作为类成员和一个“toString()”方法:

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

我有另一个扩展 User 的类“Employee”,它还包含一个“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; }
};

好吧,现在我有了另一个类“Stack”,其中包含一组用户(用户对象,而不是用户指针):

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 的默认构造函数(我必须明确地写,但我不知道那是否正确)。

最佳答案

I think, I could be getting this result because of:

  • Storing objects instead of pointers or references to objects.

正确。您正在动态分配一个 User 数组。此数组中的对象只能是 User,不能是其他对象。他们永远不是 Employee。要在 C++ 中获得多态行为,您需要使用指向 User 的指针或引用。

关于c++ - C++ 中的动态链接不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16327264/

相关文章:

c# - 从 C++/CLI 访问 TryGetMember

dynamic - Google Apps 脚本 - 谷歌表单 "go to section based on answer"

c++ - boost :为什么 write_json 改变内容

C++/限制类的实例,其他类从它继承

CSS 链接行为覆盖/继承 : FF/Chrome give random results with Wordpress customization

c# - 我应该在继承链中包含所有接口(interface)吗?

c# - 从没有反射器/ilspy 的 c# 生成 MSIL 代码

c++ - 执行 popen(),将 FILE* 指针放入 fstream,那么 pclose() 呢?

C++访问模板中的内部类

c# - 如何使用 protobuf-net 代理序列化继承链中的类型?