我是 C++ 初学者,请帮助我。 我不能使用模板类作为构造函数的参数。 xcode 显示“没有用于初始化“Work”的匹配构造函数”错误。 下面的整个源代码,任何人都可以解决这个问题吗?
#include <iostream>
class Base {
public:
virtual void hello_world() const {
printf("Base::hello_world()\n");
};
};
class Derived : public Base {
public:
void hello_world() const {
printf("Derived::hello_world()\n");
};
};
template<class T>
class Templ {
public:
Templ(const T &t) : _value(t) {}
const T& getValue() const{
return _value;
}
private:
const T &_value;
};
class Work {
public:
Work(const Templ<Base*> &base) : mBase(base) {}
void working() {
mBase.getValue()->hello_world();
}
private:
const Templ<Base*> &mBase;
};
int main(int argc, const char * argv[]) {
Templ<Base*> base(new Base());
//OK
Work w_base(base);
Templ<Derived*> derived(new Derived());
//error: No matching constructor for initialization of 'Work'
Work w_derived(derived);
return 0;
}
最佳答案
Work w_derived(derived);
永远不会像 Work
那样工作期望一个 Templ<Base*>
. Templ<Base*>
和一个 Templ<Derived*>
是两种不同的、截然不同的类型。就像std::vector<int>
与 std::vector<std::complex>
不同.
不过你可以做的是创建一个 Templ<Base*>
从指向 Dervied
的指针然后创建一个 Work
接着就,随即。有点像
Templ<Base*> derived(new Derived());
Work w_derived(derived);
另外正如评论中指出的那样,因为您使用的是多态性,所以您需要在基类中有一个虚拟析构函数。如果析构函数不是虚拟的,则只有基类析构函数会运行,您的对象将不会被正确析构。
关于C++ 模板<基类和派生类>,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38897107/