C++虚函数在子类,派生类中的定义有关问题
C++虚函数在子类,派生类中的定义问题
有个题目,如下
Which virtual function redeclarations of the Derived class are correct?
a. Base* Base::copy(Base*);
Base* Derived::copy(Derived*);
b. Base* Base::copy(Base*);
Derived* Derived::copy(Base*);
c. ostream& Base::print(int,ostream&=cout);
ostream& Derived::print(int,ostream&);
d. void Base::eval() const;
void Derived::eval();
基类Base,
我选c
有人讲讲这4个选项为什么对或不对啊?
------解决方案--------------------
同意dcbenwu(快乐小熊) 的答案。
98版C++标准支持返回值协变,并且参数是抗变的。因此a错误,b正确。
协变的定义可以网上查一下;简单的讲,就是dcbenwu(快乐小熊)说的类型的“向上兼容”。
c也正确,因为当用Base的指针调用print时,如果传递一个参数,会用Base中定义的默认参数,但是调用Derived的实现。
有个题目,如下
Which virtual function redeclarations of the Derived class are correct?
a. Base* Base::copy(Base*);
Base* Derived::copy(Derived*);
b. Base* Base::copy(Base*);
Derived* Derived::copy(Base*);
c. ostream& Base::print(int,ostream&=cout);
ostream& Derived::print(int,ostream&);
d. void Base::eval() const;
void Derived::eval();
基类Base,
我选c
有人讲讲这4个选项为什么对或不对啊?
------解决方案--------------------
同意dcbenwu(快乐小熊) 的答案。
98版C++标准支持返回值协变,并且参数是抗变的。因此a错误,b正确。
协变的定义可以网上查一下;简单的讲,就是dcbenwu(快乐小熊)说的类型的“向上兼容”。
c也正确,因为当用Base的指针调用print时,如果传递一个参数,会用Base中定义的默认参数,但是调用Derived的实现。