C++ 模板<基类和派生类>

标签 c++ templates

我是 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);

Live Example

另外正如评论中指出的那样,因为您使用的是多态性,所以您需要在基类中有一个虚拟析构函数。如果析构函数不是虚拟的,则只有基类析构函数会运行,您的对象将不会被正确析构。

关于C++ 模板<基类和派生类>,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38897107/

相关文章:

c++ - 了解 VerQueryValue

具有默认参数的 C++ 模板

c++ - 在 CEF 中管理 cookie

c++ - 数组初始化函数 : Passing Array as Pointer: C++

c++ - DLL 注入(inject)有效,除非我在 Qt Creator 中编译它

c++ - 模板特化函数 C++

c++ - 向前声明类模板显式/部分特化有什么意义?

c++ - 遍历通用 STL 容器以检查是否存在

c++ - Variadic 模板 - 如何创建存储传递参数的类型

c++ - 将 boost 与 numerical recipes 3 代码集成