如何从子班访问母班的数据?

时间:2018-10-19 04:21:00

标签: c++ class architecture instance

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

#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();
}

如何确保由func()调用的foo可以访问存储在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]'

1 个答案:

答案 0 :(得分:1)

  

从派生类访问基类内部函数的技巧是使用 virtual override 说明符对它们进行重新声明...

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

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; }
  

您必须在子类中重新定义它,因为子不能成为母亲,这就是您无法访问这些功能的原因...

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

在这里,您 必须具有与基类中完全相同的声明 (除了 virtual 外,当 override时该冗余是多余的) 用于...),并添加override说明符,以重新声明您在子类内部的基类中具有的相同功能...

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

  

注意:覆盖说明符(自 C ++ 11 起)与虚拟说明符类似,不同之处在于它仅可用于派生类/结构,并且使虚拟内部子声明的用法是可选的(在基类中,必须使用虚拟代替)...


编辑:您可以将派生类分配给基类,但是不可能相反,这就是代码失败的原因……尝试做某事的密谋像这样使用命名空间,例如:

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

亲切的问候,

Ruks。