【问题标题】:Trouble overwriting inherited static const members覆盖继承的静态 const 成员时遇到问题
【发布时间】: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


【解决方案1】:

这行不通。

    std::string type();

这是一个固定的函数,将返回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";

并实现虚函数返回每个类的字符串。

【讨论】:

  • 感谢您的帮助!非常有帮助。问题已成功解决;)
【解决方案2】:

一种选择是在构造函数中设置非静态变量_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;
}

【讨论】:

  • 在我的回答中添加了主要内容。删除了我的错误评论。这将自行编译和运行。
  • 为什么你的函数之后还有虚假的;?但实际上,其他有效的解决方案不会以少量额外内存使用为代价引入虚拟。
  • 感谢您的帮助。但是,我希望 const 值 typeStr 是它自己的类的资源,而不是它的每个实例的资源。
猜你喜欢
  • 2016-01-19
  • 1970-01-01
  • 1970-01-01
  • 2015-06-10
  • 1970-01-01
  • 1970-01-01
  • 2015-02-14
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多