Mam stałą wartość zmiennej int w mojej klasie bazowej i chciałbym zainicjować odpowiadającą w mojej klasie pochodnej, z inną wartością (jako parametr), czy jest to możliwe?C++ Inicjuje klasę podstawową "const int w klasie pochodnej?
Oto co zrobiłem:
// Base.h (methods implemented in Base.cpp in the actual code)
class Base {
public:
Base(const int index) : m_index(index) {}
int getIndex() const { return m_index; }
private:
const int m_index;
};
// Derived.h
class Derived : public Base {
public:
Derived(const int index, const std::string name) : m_name(name) {}
void setName(const std::string name) { m_name = name; }
std::string getName() const { return m_name; }
private:
std::string m_name;
};
Ale oczywiście to pyta mnie o Base::Base()
, który nie istnieje, a jeśli mogę zdefiniować ją, będę musiał podać wartość domyślną dla m_index
, czego nie robić chcę zrobić. Czy muszę oddzielnie definiować const int m_index
w każdej klasie pochodnej?
podobne pytanie, ale nie jestem pewna, czy statyczna wpływa to w żaden sposób: C++ : Initializing base class constant static variable with different value in derived class?
CO?!? Robiłem C++ przez około 3 do 4 lat lub coś takiego i nigdy nie wpadłem na to? Zawsze myślałem, że muszę użyć domyślnego konstruktora ... Dzięki stary, przyjmiesz za chwilę. –