【发布时间】:2016-12-23 18:32:53
【问题描述】:
为什么这不合法?
class Base {
public:
virtual void bar() = 0;
virtual void barc() const = 0;
};
class Derived: public Base {
public:
// deliberately omitted
// virtual void bar()
virtual void barc() const override { };
};
int main() {
const Derived b;
b.barc();
// b.bar();
// fails as expected with "passing 'const Bar' as 'this' argument discards qualifiers"
}
这失败并出现以下错误,因为我没有定义virtual void bar():
prog.cpp: In function 'int main()':
prog.cpp:16:12: error: cannot declare variable 'd' to be of abstract type 'Derived'
const Derived d;
^
prog.cpp:10:7: note: because the following virtual functions are pure within 'Derived':
class Derived : public Base{
^
prog.cpp:6:15: note: virtual void Base::bar()
virtual void bar() = 0;
但是我无论如何都不能在这里调用bar,因为那个方法没有被标记为const。如果定义了bar,是否有任何合法的方式间接调用d.bar()?
是否允许使用
const_cast?我在转换超类/子类时会遇到麻烦吗?
如果不是,那我为什么要定义它?
【问题讨论】:
-
按照编译器错误告诉你的去做。你需要定义
bar() -
@NathanOliver。虽然您显然是正确的,但我认为这不是 OP 的要求。
-
@NathanOliver:我不想定义
bar()。我希望声明非常量Bar是非法的 -
@Eric。如果您希望定义非常量
Bar是非法的,那么为什么要添加非常量bar? -
啊。我知道你现在从哪里来。基本上为什么不定义一个调用它的函数会是编译器错误是编译器错误。