Проблемы с перезаписью унаследованных статических констант - PullRequest
0 голосов
/ 28 ноября 2018

У меня есть два класса.Базовый класс - это фрукты, а производный класс - яблоко.Я использую строки типа для определения типа классов. Однако когда я попытался получить доступ к функции type () экземпляра класса apple, чтобы получить возвращение строки типа, я получил базовый класс 'string 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

Ответы [ 2 ]

0 голосов
/ 28 ноября 2018

Одним из вариантов является установка нестатической переменной _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;
}
0 голосов
/ 28 ноября 2018

Это не может работать.

    std::string type();

Это фиксированная функция, которая возвращает тип fruit.PEriod.

Если вы хотите сделать все по-своему, используйте виртуальные функции:

#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";

И реализуйте виртуальные функции для возврата строки каждого класса.

...