c++ - 从派生范围调用函数

标签 c++ inheritance c++11 scope

我有一些代码似乎与此类似:

#include <iostream>

class Base {
public:
    void test() {
        std::cout << "Base::test()" << std::endl; 
    }

    void test2() {
        test();
    }
};

class Derived : public Base {
public:
    void test() {
        std::cout << "Derived::test()" << std::endl;
    }
};

int main() {
    Derived d;
    d.test2();
    return 0;
}

现在输出当然是 Base::test(),但是我希望它输出 Derived::test() without 使用虚函数调用和对函数重载使用不同的表示法称为:Derived::test

有人知道这是否有可能实现吗?

最佳答案

您可以使用所谓的奇怪重复类型模式 (CRTP) 并生成 Base模板:

template<typename D>
class Base {
public:
    void test() {
        std::cout << "Base::test()" << std::endl;
    }

    void test2() {
        (static_cast<D*>(this))->test();
    }
};

然后,您将得出 Derived来自 Base<Derived>而不仅仅是 Base :

class Derived : public Base<Derived> {
//                     ^^^^^^^^^^^^^
//                     This is the only change required in Derived
public:
    void test() {
        std::cout << "Derived::test()" << std::endl;
    }
};

这是一个live example .

关于c++ - 从派生范围调用函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17325176/

相关文章:

c++ - 为什么我在继承程序中得到垃圾总和?

C++ 字符串流连接查询

c++ - 下面的文字中ostream和istream这两个词不是调换了吗?

C++ 编译器错误递归模板

.NET:继承修改基类(C++转换)

c++ - 遍历 unordered_set 的效率如何?

c++ - 在类中创建分数列表数组 | C++

c++ - 由 CppCMS 提供支持的实时网站

c++ - 模板类的继承问题

inheritance - 从构造函数初始化 Typescript 类值