c++ - 重载方法覆盖 : Is there any simplification?

标签 c++ c++11 overriding

我正在编写一个使用讨厌的非 C++11 代码的类的重写。不幸的是,我不允许更改父类。 它有两个同名的方法,其中一个被子类覆盖。该方法也作为参数传递给方法。我想在这里有仿函数,但正如我之前写的,我无法更改 ClassA。 简化的代码如下所示:

父类:

class CLassA
{
public:
    typedef void  (CLassA::*Method_t)(int x, int y);
    int ForAll(Method_t action, int y);
    virtual void MethodA(int x);
    virtual void MethodA(int x, int y);
};

int CLassA::ForAll(Method_t action, int x)
{
    (this->*action)(x, x);
    return x;
}

void CLassA::MethodA(int x)
{
    printf("CLassA::MethodA: %d\n", x);
    ForAll(&CLassA::MethodA, x);
}

void CLassA::MethodA(int x, int y)
{
    printf("\tCLassA::MethodA: %d %d\n", x, y);
}

我的第一个覆盖:

class CLassB : public CLassA
{
public:
    void MethodA(int x, int y) override;
};

void CLassB::MethodA(int x, int y)
{
    printf("\tCLassB::MethodA: %d %d\n", x, y);
}

我的第二个覆盖:

class CLassC : public CLassB
{
public:
    void MethodA(int x) override;
};

void CLassC::MethodA(int x)
{
    printf("CLassC::MethodA: %d\n", x);
    ForAll(&CLassC::CLassA::MethodA, x);
}

调用例程:

int main(int argc, char** argv)
{
    CLassA A;
    A.MethodA(1);

    CLassB B;
    B.CLassA::MethodA(2);

    CLassC C;
    C.MethodA(3);
    return 0;
}

输出(link):

CLassA::MethodA: 1
    CLassA::MethodA: 1 1
CLassA::MethodA: 2
    CLassB::MethodA: 2 2
CLassC::MethodA: 3
    CLassB::MethodA: 3 3

我绝对不喜欢,我必须将命名空间添加到引用和调用中 (ForAll(&CLassC::CLassA::MethodA, x);, B.CLassA::方法A(2);).

你能给我一个提示,如何避免这些难看的符号吗?

最佳答案

当您在派生类中声明一个函数时,基类中任何同名的重载都将被隐藏。无论函数是重载还是覆盖,此规则都适用。重载时virtual功能,尤其是 elwhen 他们有一个实现,正常的 appeoach 是有 public和非 virtual调用 protected 的转发函数功能。这样virtual然后可以在不影响调用接口(interface)的情况下单独覆盖函数。参见示例 std::num_get<...> .

当你重载时 virtual您无法更改基类中的函数最好的方法是使用 using 使基类重载可见声明:

class CLassB: public CLassA {
public:
    using CLassA::MethodA;
    void MethodA(int, int) override;
};

关于c++ - 重载方法覆盖 : Is there any simplification?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20043474/

相关文章:

c++ - 为什么包含 rand() 的这段 C++11 代码在多线程中比在单线程中慢?

bash - 带有参数的可覆盖预定义 Bash 变量

jquery - 如何在 yiiframework 中覆盖 jquery.yiigridview.js

c++ - 为什么 cout 在代码块上没有产生输出?

c++ - C++ 是否保证 cstdint sizeof 的顺序?

c++ - 将多态 unique_ptr 作为参数传递时发生内存泄漏

c# - 是否有一种紧凑的方式告诉 C# 编译器使用基本的 Equals 和 == 运算符?

C++ Qt 在单独的进程中运行应用程序的各个部分

c++ - 如何在桌面上的文件夹中创建文本文件

c++ - 在 Qt 项目中使用 mciSendString