我在Stackoverflow上发现了一些关于将抽象类传递给方法的问题,例如: Pass abstract parameter to method, why not?
我想尝试做类似下面的事情,但我一直都会收到错误。我尝试过各种各样的猜测,比如切换到指针等等。但没有什么真正有效。我还在: c_()
之后添加了Other
,但这也没有用。我是这门语言的新手,我还在弄清楚事情是如何结合在一起的。
#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_()
答案 0 :(得分:1)
User Id=xxx;Password=xxx; Data Source=(DESCRIPTION= (ADDRESS=(PROTOCOL=TCP) (HOST=172.xx.xx.xx) (PORT=1521)) (CONNECT_DATA=(SID=xxx)));
您需要初始化构造函数成员初始化列表中的引用:
Other(Child &c=Child2()) {
c_ = c; // << can't be done since references must be
// initialised at time of construction
}