简体   繁体   English

纯虚拟 function 调用

[英]pure virtual function calling

The first printable(e) is giving "entity" but for the next line, the program crashes.第一个printable(e)给出了“实体”,但对于下一行,程序崩溃了。 giving some characters.给出一些字符。 Let me know the error.让我知道错误。

#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);
}

Your getclassname() function doesn't return anything even though it promises it does.您的getclassname() function 不会返回任何东西,即使它承诺会返回。 This results in undefined behaviour .这会导致未定义的行为 You should not print, but instead compose a string:您不应该打印,而是编写一个字符串:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM