c++ - C++中的类型转换和继承

标签 c++ templates compiler-errors

我有一个问题。有两个类:

struct Base {
    Base* retain() {
    //retain here
        return this;
    }
};

struct Derived : Base {
};


Derived *d1 = new Derived();
Derived *d2 = d1->retain(); //error here: need to typecast to Derived*
Derived *d3 = (Derived*)d1->retain(); //OK

有没有什么方法可以以不需要手动类型转换结果的方式重写 retain() 函数?换句话说:retain() 应该返回派生类型的对象。

最佳答案

template<typename T>
struct Base
{
    T* retain()
    {
        return (T*)this;
    }
};

struct Derived : Base<Derived>
{
};


Derived *d1 = new Derived();
Derived *d2 = d1->retain();

或者:

struct Base
{
    template<typename T>
    void retain(T** ptr)
    {
        *ptr = (T*)this;
    }
};

struct Derived : Base
{
};

Derived *d1 = new Derived;
Derived *d2;
d1->retain(&d2);

关于c++ - C++中的类型转换和继承,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9953077/

相关文章:

c++ - 使用 std::vector 迭代器分配 std::string 会在一个项目中导致调试错误,但在另一个项目中有效?

c++ - libev 每个 fd 超过一个观察者失败

C++ : friend function in a template class for operator<<

c# - 无法在 Windows 7 中编译 C#

c++ - 为什么 setCentralWidget 不起作用?

c++ - 如何以编程方式创建 TTF 或 OTF 字体 [C/C++]

c++ - 模板函数作为模板类的友元

c++ - 本地类和函数模板

haskell - 如何更改 GHC 编译器错误消息的打印方式?

包 fst 的 R 编译失败