c++ - 在 C++ 中实现具有相同方法名称和不同参数的多个接口(interface)

标签 c++ visual-c++ com g++ clang

我正在尝试用 C++ 创建一个类,该类实现多个具有相同方法名称但具有不同签名的接口(interface)。

#include <string>
#include <iostream>

using namespace std;

class IA {
public:
    virtual void method(int i) = 0; // Signature is different from IB::method

    virtual ~IA() { }
};

class IB {
public:
    virtual void method(const string& s) = 0; // Signature is different from IA::method

    virtual ~IB() { }
};

class MyClass : public IA, public IB {      
    virtual void IA::method(int i) {
        cout << "IA::method " << i << endl;
    }

    virtual void IB::method(const string& s) {
        cout << "IB::method " << s << endl;
    }

    virtual ~MyClass() { }
};

此类使用 Visual C++ 2017 进行编译。但是,我想将方法​​实现与类 header 分开,但将实现移到类声明之外会导致编译错误。

例如,这不起作用:

class MyClass : public IA, public IB {
    virtual void IA::method(int i);
    virtual void IB::method(const string& s);

    virtual ~MyClass() { }
};

void MyClass::IA::method(int i) {
    cout << "IA::method " << i << endl;
}

void MyClass::IB::method(const string& s) {
    cout << "IB::method " << s << endl;
}

Visual C++ 2017 报告此错误:

"C2509 method: member function not declared in 'MyClass'"

出于好奇,我使用其他编译器(g++ 和 clang)编译了这两个类声明,但它们都无法编译。

这是 Visual C++ 特定的行为吗?

最佳答案

不需要这样标记你的函数:IA::method

区别在于签名的调用部分。

class IA {
public:
    virtual void method(int i) = 0; // Signature is different from IB::method

    virtual ~IA() { }
};

class IB {
public:
    virtual void method(const string& s) = 0; // Signature is different from IA::method

    virtual ~IB() { }
};

class MyClass : public IA, public IB {
public:    
    void method(int i) override { // No need for IA::method
        cout << "IA::method " << i << endl;
    }

    void method(const string& s) override { // No need for IB::method
        cout << "IB::method " << s << endl;
    }

    virtual ~MyClass() { }
};

关于c++ - 在 C++ 中实现具有相同方法名称和不同参数的多个接口(interface),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54175830/

相关文章:

mysql - 在 VC++ 中使用 MySQL

c# - 当我更改 C# COM dll 的签名时,为什么我必须从 x86 到 msil 再回到 x86

c++ - 将 Windows C++ 项目从 Qt4 移动到 5 会出现数百个看似不相关的编译错误

c++ - 指向 objc 类成员方法的函数指针,用于 C++?

c - 如何在没有 __uuidof 的情况下从 C 调用 DXGI

c++ - GetFileAttributes 因绝对路径而失败

java - 使用图表 X 的 VC++ 图表

c++ - 使用 tlb 文件的 COM 自动化

c++ - 进程返回 255 (0xff) 个代码块

c++ - 在附加数据库的空表/ View 中查找 SQLite 列名