如何从 child class 访问母亲 class 的数据?

How to access data of mother class from child class?

如何在不创建实例的情况下从 child class 访问母亲 class 的数据? 我有类似的东西:

#include <iostream>
class mother {
    private:

    public:
        mother(){}
        virtual ~mother(){}
        virtual void func() const {std::cout << "mother " << dat <<std::endl;}
        virtual void dat_set(std::string arg){dat=arg;}
        std::string dat;
};

class child:mother {
    public:
        child(){}
        ~child(){}
        void dat_set(std::string const arg) override { mother::dat_set(arg); }
        void func() const override { std::cout << "child " << mother::dat << std::endl; }
};

int main (void) {
    auto tmp = new mother();
    tmp->dat_set("test");
    auto foo = new child();
    foo->func();
}

如何确保 foo 调用的 func() 可以访问存储在 mother 中的数据?

编辑 我不应该让 std::string dat 变成 static std::string dat 吗?我试过了,但是我得到了

这样的编译器错误
/tmp/ccZV7Y4n.o: In function `child::func()':
main.cpp:(.text._ZN5child4funcEv[_ZN5child4funcEv]+0x1d): undefined reference to `mother::dat[abi:cxx11]'

The trick to accessing functions inside base classes from derived classes is to redeclare them using virtual and override specifiers...

首先,创建析构函数 virtual...(因为您的编译器不希望 class 中没有虚析构函数的虚函数

virtual ~mother() = default; // If the compiler is happy, we all are happy...

然后让你的函数虚拟...

virtual void dat_set(std::string const arg) { dat = arg; }
virtual void func() const { std::cout << "mother " << dat << std::endl; }

You have to define it again inside the child class since the child cannot become the mother, and that is the reason you cannot access those functions...

void dat_set(std::string const arg) override { mother::dat_set(arg); }
void func() const override { mother::func(); }

在这里你必须有你在基础class中的完全相同的声明(除了virtual 在使用 override 时是多余的...) 并添加 override 说明符 re-declares 与您在基础中具有的相同功能class 里面 child class...

对于行为只需输入 mother::func()mother::dat_set(/*params go here*/) 用于调用带有参数的函数,我打赌你可能已经知道 )来调用相应的函数函数...

Note: The override specifier (since C++11) is similar to the virtual specifier, except that it is only usable in dervied classes/structures, and makes the usage of virtual inside child declarations optional (In your base class you have to use virtual instead)...


编辑: 您可以将派生的 class 分配给基数 class 但不可能相反,这就是原因为什么你的代码失败了......做这样的事情的近距离尝试是使用名称空间,例如:

namespace some_namespace
{
    static std::string dat;
    // The child and mother class declarations and other things go here...
}

亲切的问候,

卢克。