【发布时间】:2010-04-07 13:50:51
【问题描述】:
使用 VC71 编译器并得到编译器错误,我不明白。 例子来了
class A
{
public:
virtual int& myMethod() = 0;
virtual const int& myMethod()const = 0;
};
class B: public A
{
public:
// generates: error C3241: 'const int &B::myMethod(void)' : this method was not introduced by 'A'
virtual int& A::myMethod();
// error C2555: 'B::myMethod': overriding virtual function return type differs and is not covariant from 'A::myMethod'
virtual const int& A::myMethod() const;
};
当我在 B 中切换两个方法定义的顺序时,我会看到不同的编译器错误:
class B: public A
{
public:
// error C3241: 'const int &B::myMethod(void)' : this method was not introduced by 'A'
virtual const int& A::myMethod() const;
// error C2556: 'int &B::myMethod(void)' : overloaded function differs only by return type from 'const int &B::myMethod(void)'
// error C2373: 'B::myMethod' : redefinition; different type modifiers
virtual int& A::myMethod();
// error C2555: 'B::myMethod': overriding virtual function return type differs and is not covariant from 'A::myMethod'
};
但是,如果我省略了 A:: 东西,那么我不会收到任何编译器错误:
class B: public A
{
public:
virtual int& myMethod();
virtual const int& myMethod() const;
};
那么,我的方法名称前面的 A:: 到底是什么,为什么我会看到这些不同的编译器错误?欢迎任何解释!
【问题讨论】:
-
为什么您首先将所有这些 A:: 放在您的代码中?你想达到什么目的?我认为我从未在这种情况下使用过这种语法(这似乎是一个非常简单的继承)。
-
@Daniel:我承认,我真的不知道自己在做什么。我曾希望,如果有人更改 A 中的虚拟方法名称,那么我会在 B 的覆盖定义中看到编译器错误。省略 A:: 时,编译器不知道我是尝试覆盖 A 的方法还是引入自己的方法,如果 A 处不存在此类方法定义,编译器不会产生错误。这有意义吗?
-
如果您想要该功能,请使用 C 而不是 C++。 :P
-
@Stefan:你是说你想保证 A 在 B 中实现了一些功能?如果删除 virtual 关键字,则不会覆盖基类。
-
@Stefan:你可能对这个问题感兴趣,然后:stackoverflow.com/questions/497630/…
标签: c++ visual-c++ compiler-errors