我在cpp中有一个声明,其函数如下:
virtual void funcFoo() const = 0;
Run Code Online (Sandbox Code Playgroud)
我假设如果声明显式,可以由另一个类继承,但是它们之间的区别是什么
virtual void funcFoo() = 0;
Run Code Online (Sandbox Code Playgroud)
对我来说重要的是改进我的编程,我想知道其中的区别.我不希望遗传不良引起的故障.
提前致谢.
jua*_*nza 33
第一个签名意味着可以在派生类型的const实例上调用该方法.不能在const实例上调用第二个版本.它们是不同的签名,因此通过实现第二个,您不会实现或覆盖第一个版本.
struct Base {
virtual void foo() const = 0;
};
struct Derived : Base {
void foo() { ... } // does NOT implement the base class' foo() method.
};
Run Code Online (Sandbox Code Playgroud)
fel*_*ipe 14
virtual void funcFoo() const = 0;
- You can't change the state of the object
- You can call this function via const objects
- You can only call another const member functions on this object
virtual void funcFoo() = 0;
- You can change the state of the object
- You can't call this function via const objects
Run Code Online (Sandbox Code Playgroud)
关于const correctectness的最好的教程或Faq是parashift的C++ FAQ:
看看:http://www.parashift.com/c++-faq-lite/const-correctness.html