2012-11-27 19 views
6

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?

Odpowiedz

13

Wystarczy zadzwonić pod odpowiedni Base konstruktora w liście inicjalizacji Derived „s

Derived(const int index, const std::string name) : Base(index), m_name(name) {} 
+1

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ę. –

1

You można wywołać konstruktora bazowego w następujący sposób:

class B1 { 
    int b; 
public:  
    // inline constructor 
    B1(int i) : b(i) {} 
}; 

class B2 { 
    int b; 
protected: 
    B2() {}  
    // noninline constructor 
    B2(int i); 
}; 

class D : public B1, public B2 { 
    int d1, d2; 
public: 
    D(int i, int j) : B1(i+1), B2(), d1(i) 
    { 
    d2 = j; 
    } 
}; 

Ponieważ c + +11 Twój może nawet użyć konstruktorów tej samej klasy. Ta funkcja nazywa się konstruktorami delegującymi.

Derived(){} 
Derived(const int index, const std::string name) : Derived() {} 
Powiązane problemy