c++ - 纯虚函数调用
问题描述
第一个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);
}
解决方案
您的getclassname()
函数不会返回任何内容,即使它承诺会返回。这会导致未定义的行为。您不应该打印,而是编写一个字符串:
string getclassname() override
{
return "player";
}
推荐阅读
- docker - Dockerfile ENV var 字符替换
- scala - 用新数据改造现有的 Spark ML PipelineModel
- java - 计算和打印文本文件中每个字母的出现次数
- swift - 如何快速检索唯一 ID 以将其删除(Firebase)
- docker - 拉取的 Docker 镜像配置文件在哪里
- html - VBA 中的网页抓取,其中某些 HTML 信息无法引用
- html - 我怎样才能让 wget 从这个网站下载所有的 pdf 文件?
- python - 将 django 项目部署到 PythonAnywhere 时出现“ModuleNotFoundError: No module named 'bootstrap4'”
- json - 如何从 VB.Net 中的另一个 JSON 对象创建新的 JSON 对象?
- swift - 没有为组件类型注册存储