2012-03-25 48 views
0

重写基类的常量方法从派生类

class Base{ 
//... 
    public: 
    int get()const{ // const 
    // Do something. 
    } 
    int get(int x){ 
    // Do Someting. 
    } 

    //... 

}; 
class Derived:public Base{ 
//.... 
    public: 
    int get(){ // not const (not the same signature as the one is the base class) 
    //Dosomething 
    } 
     //... 

}; 

我知道,获得()的派生类将隐藏get()和获取(INT X)的基类中的方法。所以我的问题是:
1)这是conconred重载或覆盖?
2)在派生类中get()const会改变一些内容(隐藏或不隐藏基类方法)。

“这是一个常见的错误隐藏基类的方法,当你打算重写它,通过 忘记包括关键字const常量是签名的一部分,和:从C++的书

报价离开它关闭 改变了签名,从而隐藏方法,而不是覆盖它。“

+0

重载:http://en.wikipedia.org/wiki/Function_overloading,覆盖:http://en.wikipedia.org/wiki/Method_overriding – alfa 2012-03-25 18:54:07

+0

第二个得到基地错过了返回类型 – 2012-03-25 18:56:56

回答

6

它既不重载也不重写。相反,它是隐藏

如果其他功能也是可见的,它被超载,您可以用using实现:

class Derived : public Base 
{ 
public: 
    using Base::get; 
    int get(); 
}; 

即使你宣布在派生类中int get() const,它只会躲在基地功能,因为基本功能不是virtual

+0

1)所以重写的唯一情况是让Derived类中的get函数可见?
2)不会给我一个错误,因为它是多重定义? – AlexDan 2012-03-25 19:06:38

+0

@AlexDan:不,唯一的重写方法是使'get' * virtual *,然后在'Derived'中用相同的签名声明另一个函数。 – 2012-03-25 19:08:11

+0

你用前面提到的方法怎么样,用'使用'关键字。这是否超越了压倒一切?你可以向我解释Derived类中关键字'using'的用法。并抱歉所有这个问题。 012 – AlexDan 2012-03-25 19:12:40

2
  1. 都不是,它只是‘隐藏’。

  2. 编号隐藏是根据函数名而不是函数签名发生的。

只有声明了基类功能virtual;你不能覆盖一个非virtual函数。

+0

我读了一本书:Quote“这是一个常见的错误,当你打算重写它时隐藏一个基类方法, 忘记了包含关键字const。const是签名的一部分,并且将它关闭 更改签名,从而隐藏方法而不是重写它。“你能解释给我吗?谢谢 – AlexDan 2012-03-25 18:55:26

+0

@AlexDan:看到我更新的答案。 – 2012-03-25 18:55:41

相关问题