64

有两个基类具有相同的函数名。我想继承它们,并以不同的方式覆盖每种方法。如何使用单独的声明和定义(而不是在类定义中定义)来做到这一点?

#include <cstdio>

class Interface1{
public:
    virtual void Name() = 0;
};

class Interface2
{
public:
    virtual void Name() = 0;
};

class RealClass: public Interface1, public Interface2
{
public:
    virtual void Interface1::Name()
    {
        printf("Interface1 OK?\n");
    }
    virtual void Interface2::Name()
    {
        printf("Interface2 OK?\n");
    }
};

int main()
{
    Interface1 *p = new RealClass();
    p->Name();
    Interface2 *q = reinterpret_cast<RealClass*>(p);
    q->Name();
}   

我未能在 VC8 中将定义移出。我发现 Microsoft 特定关键字 __interface 可以成功完成这项工作,代码如下:

#include <cstdio>

__interface Interface1{
    virtual void Name() = 0;
};

__interface Interface2
{
    virtual void Name() = 0;
};

class RealClass: public Interface1,
                public Interface2
{
public:
    virtual void Interface1::Name();
    virtual void Interface2::Name();
};

void RealClass::Interface1::Name()
{
    printf("Interface1 OK?\n");
}

void RealClass::Interface2::Name()
{
    printf("Interface2 OK?\n");
}

int main()
{
    Interface1 *p = new RealClass();
    p->Name();
    Interface2 *q = reinterpret_cast<RealClass*>(p);
    q->Name();
}  

但是还有另一种方法可以在其他编译器中使用更通用的方法吗?

4

5 回答 5

80

这个问题并不经常出现。我熟悉的解决方案是由 Doug McIlroy 设计的,并出现在 Bjarne Stroustrup 的书中(在C++ 的设计与进化第 12.8 节和C++ 编程语言第 25.6 节中都有介绍)。根据Design & Evolution中的讨论,有人提出优雅地处理这种特定情况,但被拒绝了,因为“这种名称冲突不太可能变得普遍到足以保证单独的语言功能”,并且“不太可能成为日常为新手工作。”

您不仅需要Name()通过指向基类的指针进行调用,还需要一种方式来说明在对派生类进行操作时要使用哪个。 Name()该解决方案增加了一些间接性:

class Interface1{
public:
    virtual void Name() = 0;
};

class Interface2{
public:
    virtual void Name() = 0;
};

class Interface1_helper : public Interface1{
public:
    virtual void I1_Name() = 0;
    void Name() override
    {
        I1_Name();
    }
};

class Interface2_helper : public Interface2{
public:
    virtual void I2_Name() = 0;
    void Name() override
    {
        I2_Name();
    }
};

class RealClass: public Interface1_helper, public Interface2_helper{
public:
    void I1_Name() override
    {
        printf("Interface1 OK?\n");
    }
    void I2_Name() override
    {
        printf("Interface2 OK?\n");
    }
};

int main()
{
    RealClass rc;
    Interface1* i1 = &rc;
    Interface2* i2 = &rc;
    i1->Name();
    i2->Name();
    rc.I1_Name();
    rc.I2_Name();
}

不漂亮,但决定是它并不经常需要。

于 2010-01-05T09:44:25.243 回答
8

您不能单独覆盖它们,您必须同时覆盖它们:

struct Interface1 {
  virtual void Name() = 0;
};

struct Interface2 {
  virtual void Name() = 0;
};

struct RealClass : Interface1, Interface2 {
  virtual void Name();
};
// and move it out of the class definition just like any other method:
void RealClass::Name() {
  printf("Interface1 OK?\n");
  printf("Interface2 OK?\n");
}

您可以使用中间基类模拟单个覆盖:

struct RealClass1 : Interface1 {
  virtual void Name() {
    printf("Interface1 OK?\n");
  }
};

struct RealClass2 : Interface2 {
  virtual void Name() {
    printf("Interface2 OK?\n");
  }
};

struct RealClass : RealClass1, RealClass2 {
  virtual void Name() {
    // you must still decide what to do here, which is likely calling both:
    RealClass1::Name();
    RealClass2::Name();

    // or doing something else entirely

    // but note: this is the function which will be called in all cases
    // of *virtual dispatch* (for instances of this class), as it is the
    // final overrider, the above separate definition is merely
    // code-organization convenience
  }
};

此外,您使用 reinterpret_cast 不正确,您应该:

int main() {
  RealClass rc; // no need for dynamic allocation in this example

  Interface1& one = rc;
  one.Name();

  Interface2& two = dynamic_cast<Interface2&>(one);
  two.Name();

  return 0;
}

这是用CRTP进行的重写,可能是您想要的(或不是):

template<class Derived>
struct RealClass1 : Interface1 {
#define self (*static_cast<Derived*>(this))
  virtual void Name() {
    printf("Interface1 for %s\n", self.name.c_str());
  }
#undef self
};

template<class Derived>
struct RealClass2 : Interface2 {
#define self (*static_cast<Derived*>(this))
  virtual void Name() {
    printf("Interface2 for %s\n", self.name.c_str());
  }
#undef self
};

struct RealClass : RealClass1<RealClass>, RealClass2<RealClass> {
  std::string name;
  RealClass() : name("real code would have members you need to access") {}
};

但请注意,您现在不能在 RealClass 上调用 Name(使用虚拟调度,例如rc.Name()),您必须首先选择一个基。self 宏是一种清理 CRTP 强制转换的简单方法(通常成员访问在 CRTP 库中更为常见),但可以改进。在我的其他答案之一中简要讨论了虚拟调度,但如果有人有链接,肯定会更好。

于 2010-01-05T08:42:07.607 回答
6

过去我不得不做这样的事情,但在我的情况下,我需要从一个接口继承两次并且能够区分对每个接口进行的调用,我使用了一个模板填充程序来帮助我......

像这样的东西:

template<class id>
class InterfaceHelper : public MyInterface
{
    public : 

       virtual void Name() 
       {
          Name(id);
       }

       virtual void Name(
          const size_t id) = 0;  
}

然后,您从两次派生InterfaceHelper而不是从两次派生,并为每个基类MyInterface指定不同的。id然后,您可以通过强制转换为正确的InterfaceHelper.

你可以做一些稍微复杂的事情;

class InterfaceHelperBase
{
    public : 

       virtual void Name(
          const size_t id) = 0;  
}


class InterfaceHelper1 : public MyInterface, protected InterfaceHelperBase
{
    public : 

       using InterfaceHelperBase::Name;

       virtual void Name() 
       {
          Name(1);
       }
}

class InterfaceHelper2 : public MyInterface, protected InterfaceHelperBase
{
    public : 

       using InterfaceHelperBase::Name;

       virtual void Name() 
       {
          Name(2);
       }
}

class MyClass : public InterfaceHelper1, public InterfaceHelper2
{
    public :

      virtual void Name(
          const size_t id)
      {
          if (id == 1) 
          {
              printf("Interface 1 OK?");
          }
          else if (id == 2) 
          {
              printf("Interface 2 OK?");
          }
      }  
}

请注意,上面没有看到编译器...

于 2010-01-05T09:42:35.200 回答
3
class BaseX
{
public:
    virtual void fun()
    {
        cout << "BaseX::fun\n";
    }
};

class BaseY
{
public:
    virtual void fun()
    {
        cout << "BaseY::fun\n";
    }
};


class DerivedX : protected BaseX
{
public:
    virtual void funX()
    {
        BaseX::fun();
    }
};

class DerivedY : protected BaseY
{
public:
    virtual void funY()
    {
        BaseY::fun();
    }
};


class DerivedXY : public DerivedX, public DerivedY
{

};
于 2010-01-06T09:17:38.977 回答
2

还有另外两个相关问题询问几乎(但不完全)相同的事情:

从继承的共享方法名称中挑选。如果你想让 rc.name() 调用 ic1->name()ic2->name()。

覆盖来自(模板化)基类的共享方法名称。与您接受的解决方案相比,这具有更简单的语法和更少的代码,但不允许从派生类访问函数。或多或少,除非您需要能够从 rc 调用 name_i1(),否则您不需要使用 InterfaceHelper 之类的东西。

于 2010-01-06T01:20:55.660 回答