【发布时间】:2016-10-10 09:53:27
【问题描述】:
下面的代码出现以下链接器错误:
undefined reference toIBase::Name() const'`
注意在 Base 类中,它调用了虚函数 Name()。目的是调用 Derived 类的 Name 实现,但链接器正在寻找 IBase::Name,而不是 Derived::Name()。如何解决?
template<class T_Extendable>
class IBase
{
public:
virtual ~IBase() = default;
virtual const std::string& Name() const = 0;
};
template<class T_Extendable>
class Base : public IBase<T_Extendable>
{
public:
virtual ~Base() { "Destructing " << Name(); } // use virtual function Name()
};
class Derived : public Base<Foo>
{
public:
virtual ~Derived() = default;
const std::string& Name() const final { return "Derived"; } // implement pure virtual method IBase::Name()
};
【问题讨论】:
-
const std::string& Name() const final { return "Derived"; }是灾难的根源。你的编译器应该警告你返回一个临时的引用,看看这意味着什么。 -
一定喜欢stackoverflow!当然,这看起来不像我们的生产代码,这是为了传达问题而提炼出来的。不过,我认为 Smeeheey 正在做某事。