为什么在两个编译器上结果不一样啊。请高手指教
- C/C++ code
//---test.cpp----//compile with: cl test.cppstruct B{ void operator[](int index) const{}};struct C{ void operator[](int index) const{ }};struct A:public B, public C{};void main(){ A a; a[1];}在vc2005中是下面结果,没有编译错误。
Microsoft (R) 32-bit C/C++ Optimizing Compiler Version 14.00.50727.762 for 80x86
Copyright (C) Microsoft Corporation. All rights reserved.
test.cpp
Microsoft (R) Incremental Linker Version 8.00.50727.762
Copyright (C) Microsoft Corporation. All rights reserved.
/out:test.exe
test.obj
但是在哦Orcas上面是:
Microsoft (R) 32-bit C/C++ Optimizing Compiler Version 15.00.20706.05 for 80x86
Copyright (C) Microsoft Corporation. All rights reserved.
test.cpp
test.cpp(19) : error C2593: 'operator [' is ambiguous
test.cpp(3): could be 'void B::operator [](int) const'
test.cpp(8): or 'void C::operator [](int) const'
while trying to match the argument list '(A, int)'
为什么不一样啊,是某一个编译器的bug吗,还是编译器有改变或改进。
[解决办法]
装个gcc再试。另外,自己试一下到底vc2005调用了哪个[]。
[解决办法]
那么,你应该知道结论了:不要写挑战编译器的代码。
[解决办法]
primer说过(大概是这样)即使多继承的不同父类里几个同名函数可以构成重载,在调用的时候也需要显式指定
何况你的情况是两个同名函数的签名也类似
[解决办法]
在c++标准中, 别说你这两个函数参数完全相同, 就算是不一样的参数, 都会出现编译错误.
在多重继承中, 如果两个父类拥有同样名字的函数, 将会出现二义性, 无论参数是否相同, 均不会发生重载. 调用他们的唯一办法是显示的指明他们的域(父类名).
举个例子:
- C/C++ code
#include <iostream>using namespace std;class F1{public: void foo(int i) {cout<<"f1 ="<<i<<endl;}};class F2{public: void foo(int i, int j) { cout<<"f2="<<i<<' '<<j<<endl;}};class S1 : public F1, public F2{};int main(){ S1 s; s.F1::foo(10); //OK s.F2::foo(10, 20); //OK s.foo(30); //错误, 二义性的调用 s.foo(30, 40); //错误, 二义性的调用 return 0;}