简体   繁体   中英

C++ Templates and Derived Classes Member Initialization

I'm trying to initializate a member of a base class inside a derived class constructor.

template <typename T, int D>
class BaseClass {
    // ...
protected:
    T values[D];
};

template<typename T>
class DerivedClass : public BaseClass<T, 3> {
public:
    using BaseClass<T, 3>::values;

    DerivedClass(T a, T b, T c) : values{a, b, c} {}
};

However I get this:

error: 'using BaseClass<T, 3>::values' is not a non-static data member of 'DerivedClass<T>'
  DerivedClass(T a, T b, T c) : values{a, b, c} {}
                                ^

Why isn't this allowed?

Also, I could assign values in the constructor body, but I won't be able to use initialization lists anymore.

You cannot directly initialise base class member in a derived class constructor. using you tried to use changes access from protected to public, but does not change this general rule. Create appropriate base class constructor and pass the initialisers to it in the derived class.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM