具有相同名称的纯虚函数的不同实现 [英] Distinct implementations for pure virtual functions with same name
问题描述
可能重复:
继承共享方法名称的接口
我有两个基类 I1
和 I2
与纯虚函数 void R 0;
。我想让派生类 IImpl
继承 I1
和 I2
并且有 I1 :: R()
和 I2 :: R()
的不同实现。
I have two base classes I1
and I2
with pure virtual functions void R() = 0;
. I want the derived class IImpl
to inherit from I1
and I2
and to have distinct implementations for I1::R()
and I2::R()
.
以下代码在MS VS 2005和2010中编译和工作。我在语言扩展禁用和警告级别4下编译。没有警告和错误。
The code below compiles and works in MS VS 2005 and 2010. I compile with Language Extension disabled and on warning level 4. There are no warnings and no errors.
我在gcc 4.2中尝试过相同的代码。它不编译。 GCC报告错误:
I tried the same code in gcc 4.2. It does not compile. GCC reports an error:
error: cannot define member function 'I1::R' within 'IImpl'
我的问题是:
- 为什么这段代码在MS VS中工作,为什么它不能在gcc中工作?
- 代码是标准C ++吗?
- 实现它的正确方法是什么,因此它是一个标准C ++并在VS和gcc上编译?
谢谢!
#include <stdio.h>
class I1
{
public:
virtual void R() = 0;
virtual ~I1(){}
};
class I2
{
public:
virtual void R() = 0;
virtual ~I2(){}
};
class IImpl: public I1, public I2
{
public:
virtual void I1::R()
{
printf("I1::R()\r\n");
}
virtual void I2::R()
{
printf("I2::R()\r\n");
}
};
int main(int argc, char* argv[])
{
IImpl impl;
I1 *p1 = &impl;
I2 *p2 = &impl;
p1->R();
p2->R();
return 0;
}
推荐答案
,根据8.3 / 1
This code is non-standard, according to 8.3/1
声明符-id除了成员函数(9.3)成员(9.4)在类外,...
A declarator-id shall not be qualified except for the definition of a member function (9.3) or static data member (9.4) outside of its class,...
,所以你不能限定成员函数名声明/班上。这就是为什么它不是由gcc编译。
so you can't qualify member function names when declaring/defining them inside the class. That's why it isn't compiled by gcc.
MSVC似乎有一个非标准扩展允许这样的代码。我想这是为C ++管理扩展,这是明确的接口实现是如此做,虽然它很久以前已被弃用,似乎仍然支持语法。
MSVC seems to have a non-standard extension allowing such code. I guess it was done for Managed Extensions for C++, that's exactly how explicit interface implementations were done there and although it was deprecated long ago seems that syntax is still supported.
A正确的方式,它在链接由BjörnPollex提供。
A correct way to implent it is decribed at the link provided by Björn Pollex.
这篇关于具有相同名称的纯虚函数的不同实现的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!