【发布时间】:2019-04-30 12:29:23
【问题描述】:
我有两节课。基类是fruit,派生类是apple。我使用类型字符串来识别类的类型。但是,当我尝试访问类 apple 实例的 type() 函数以获取其类型字符串的返回时,我得到了基类的类型字符串“fruit”而不是“苹果”。我应该怎么做才能解决这个问题? 这是我的代码:
#include <string>
class fruit
{
public:
std::string type();
private:
static const std::string _typeStr;
}
const std::string fruit::_typeStr = "fruit";
std::string fruit::type()
{
return _typeStr;
}
class apple:public fruit
{
private:
static const std::string _typeStr;
}
const std::string apple::_typeStr = "apple";
在 main.cpp 文件中:
#include <iostream>
#include "fruit.h"
int main()
{
apple::apple a;
cout<<a.type()<<endl;
return 1;
}
在输出中:
fruit
【问题讨论】:
-
你只能覆盖
virtual方法。
标签: c++ oop overwrite static-members