无法覆盖继承的静态常量成员

Trouble overwriting inherited static const members

我有两个 class。基础 class 是水果,派生 class 是苹果。我使用类型字符串来识别 classes.However 的类型,当我试图访问 class apple 实例的 type() 函数以获取其类型字符串的 return 时,我得到基本 class' 类型字符串 "fruit" 而不是 "apple"。我应该怎么做才能解决这个问题? 这是我的代码:

#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

这行不通。

    std::string type();

这是一个固定函数,将 return fruit 输入。期间。

如果您想按自己的方式做事,请使用虚函数:

#include <string>
class fruit
{
public:
    virtual ~fruit() = default;
    virtual const std::string& type(); // (return _typeStr)
private:
    static const std::string _typeStr;
}
const std::string fruit::_typeStr = "fruit";
std::string fruit::type()
{
    return _typeStr;
}
class apple:public fruit
{
public:
    const std::string& type() override; // (return _typeStr; will return apple::_typeStr)
private:
    static const std::string _typeStr;
}
const std::string apple::_typeStr = "apple";

并将虚函数实现到 return 每个 class 的字符串。

一种选择是在构造函数中设置非静态变量 _typeStr。

#include <iostream>
#include <string>

using namespace std;

class fruit
{
public:
    fruit()
        : _typeStr("fruit"){};
    fruit(const char *type)
        : _typeStr(type){};
    std::string type();

protected:
    const std::string _typeStr;
};

std::string fruit::type()
{
    return _typeStr;
}

class apple : public fruit
{
public:
    apple()
        : fruit("apple"){};
};

int main()
{
    apple a;
    cout << a.type() << endl;
    return 1;
}