c++ - 继承返回 *this 的成员函数

标签 c++ inheritance this

为什么 *thisderived<T>类仍然是base<T>类型?

我以为 typename X会处理的。

如果这看起来很难看,什​​么是更好的方法?

失败的尝试:

template <typename T>
class Derived;

template <typename T, typename X>
class Base{
    public:
        T val;
        X f(void){
            return *this;
        }
};

template <typename T>
class Derived: public Base<T, Derived<T> >{
};


int main(void){
    Derived<int> B;
    Derived<int> C = B.f();
}

错误:

test4.cpp(9): error: no suitable user-defined conversion from "Base<int, Derived<int>>" to "Derived<int>" exists
              return *this;
                     ^
          detected during instantiation of "X Base<T, X>::f() [with T=int, X=Derived<int>]" at line 20

compilation aborted for test4.cpp (code 2)

最佳答案

你可以用以下方式来做沮丧:

X f(){ return static_cast<X&>(*this);} 

关于c++ - 继承返回 *this 的成员函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39603261/

相关文章:

c++ - 检测基类分配给指向派生类的引用

c++ - 从类返回引用到 this

c++ - 在 VC++ 中查找导致警告 4503 的代码

c++ - 从客户端获取输入到服务器

C++ 编译器错误 C2440

java - C/C++ 和 Java 的调试器

c# - 如果两个类继承一个静态字段,那么这些类的对象是否将共享相同的值?

java如何在实现父方法的同时扩展一个类

javascript - 在 jQuery 插件中使用箭头函数

jQuery - 通过 $(this) 访问层次结构上五层的父 <li>