首页 > 解决方案 > 纯虚函数调用

问题描述

第一个printable(e)是给出“实体”,但对于下一行,程序崩溃了。给出一些字符。让我知道错误。

#include<iostream>
using namespace std;

class A
{
public:
    virtual string getclassname() = 0;
};

class entity : public A
{
public:
    string getclassname() override
    {
        cout << "entity" << endl;
    }
};

class player : public entity
{
private:
    string m_name2;

public:
    player(const string& name2) // Creating a constructor
        :m_name2(name2) {}

    string getname()
    {
        return m_name2;
    }
public:
    string getclassname() override
    {
        cout << "player" << endl;
    }
};

void printable(A* en)
{
    cout << en->getclassname() << endl;
}

int main()
{
    entity* e = new entity();
    player* p = new player("bird");

    printable(e);
    printable(p);
}

标签: c++inheritancevirtual-functions

解决方案


您的getclassname()函数不会返回任何内容,即使它承诺会返回。这会导致未定义的行为。您不应该打印,而是编写一个字符串:

string getclassname() override
{
    return "player";
}

推荐阅读