如何在c++中继承受保护的静态成员

rn0zuynd  于 2023-03-14  发布在  其他
关注(0)|答案(2)|浏览(98)

我有一个Class. h,其中我有这样的类:

class A {
protected:
    static int abc;
...

class B : public A {
...
}

我尝试在Class.cpp中定义abc为B的成员,如下所示:

int B::abc = 123;

我有这个错误:ISO C++不允许将“A::sabc”定义为“B::abc”
我该怎么做呢?

6yjfywim

6yjfywim1#

将其更改为:

int A::abc = 123;
4zcjmb1e

4zcjmb1e2#

我曾经遇到过一个具体的问题。下面是我解决问题的一个类似方法。

#include <iostream>

// Class A
class A {
    private:
        static int staticValue;
    public:
        A();
        ~A();

        virtual int getStaticValue();
};

int A::staticValue = 1;

A::A() {}
A::~A() {}

int A::getStaticValue() {
    return staticValue;
}

// Class B
class B : public A {
        private:
            static int staticValue;
        public:
            B();
            ~B();
        
            virtual int getStaticValue();
};

int B::staticValue = 2;

B::B() {}
B::~B() {}

int B::getStaticValue() {
    return staticValue;
}

int main() {
    A a = A();
    B b = B();

    std::cout << a.getStaticValue() << std::endl;
    std::cout << b.getStaticValue() << std::endl;
}

相关问题