c++ - 将抽象类(所有虚拟的,因此接口(interface))传递到另一个类的构造函数中并具有默认值

标签 c++ inheritance

我在 Stackoverflow 上发现了一些关于将抽象类传递给方法的问题,例如Pass abstract parameter to method, why not?

我想尝试执行如下所示的操作,但我不断收到错误。我尝试过各种猜测,例如切换到指针等。但没有任何效果。我还在 Other 之后添加了 : c_(),但这也不起作用。我是这门语言的新手,仍在弄清楚事物是如何组合在一起的。

#include <iostream>

class Child
{
public:
        virtual void Test() = 0;
};

class Child1 : public Child
{
public:
        void Test()
        {
                std::cout << "Child1" << std::endl;
        }
};

class Child2 : public Child
{
public:
        void Test()
        {
                std::cout << "Child2" << std::endl;
        }
};

class Other
{
Child &c_;
public:
        Other(Child &c=Child2())
        {
                c_ = c;
        }
        void which_child()
        {
                c_.Test();
        }
};

int main()
{
        Child1 c1;
        Other o(c1);
        o.which_child();
        return 0;
}

我遇到的错误:

test.cpp:31:22: error: non-const lvalue reference to type 'Child' cannot bind to a temporary of type 'Child2'
        Other(Child &c=Child2())
                     ^ ~~~~~~~~
test.cpp:31:22: note: passing argument to parameter 'c' here
test.cpp:31:9: error: constructor for 'Other' must explicitly initialize the reference member 'c_'
        Other(Child &c=Child2())
        ^
test.cpp:29:8: note: declared here
Child &c_;
       ^
2 errors generated.

添加c_()后得到这个:

test.cpp:31:22: note: passing argument to parameter 'c' here
test.cpp:31:36: error: reference to type 'Child' requires an initializer
        Other(Child &c=Child2()) : c_()

最佳答案

Other(Child &c=Child2()) {
      c_ = c; // << can't be done since references must be
              // initialised at time of construction
}

您需要初始化构造函数成员初始值设定项列表中的引用:

Other(Child &c) : c_(c) {
}

关于c++ - 将抽象类(所有虚拟的,因此接口(interface))传递到另一个类的构造函数中并具有默认值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32211321/

相关文章:

c++ - 具有挑战性的数据文件格式,需要读入包含类对象的数组变量

c++ - 如果已经被互斥锁保护,我是否需要使用 atomic<>

c++ - 如何在与用户给定前缀匹配的字符串 vector 中找到第一个单词?

javascript - 方法内的属性显示未定义但在方法外工作。如何修复它?

c++ - 从 BaseClass* 到 DerivedClass* 的无效转换

java - 派生类中的实例变量与父类(super class)的私有(private)实例变量同名吗?

c++ - OpenGL SuperBible 6 第一个例子报错

c++ - XML 中的 UTF 8 编码日文字符串

java - 主要调用太多类?

java - 为什么子类getter返回其父类(super class)的属性?