我在 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/