G****A 发帖数: 4160 | 1 The question is inspired by Item 38 in <>. Given
following code,
*****************
enum ShapeColor { RED, GREEN, BLUE };
class Shape {
public:
virtual void draw(ShapeColor color = RED) const = 0;
...
};
class Rectangle: public Shape {
public:
//definition of draw() goes here.
...
};
********************
How to define the draw() in Rectangle so that it comes with a default
parameter value other than RED?
NOTE: the article did mention that a definition like this will not work:
**********
virtual void draw(ShapeColor color = GREEN) const;
********** | P********e 发帖数: 2610 | 2 不记得ec++说什么了,但是,default argument不是function signature,所以
override的时候, base/derived可以有不同default argument value 。
virtual除了function definition是动态绑定,其他都是静态绑定,包括这个value.
所以在用pointer->draw()的时候,灭有办法确定 draw() 在name lookup时候,一定是
GREEN。
【在 G****A 的大作中提到】 : The question is inspired by Item 38 in <>. Given : following code, : ***************** : enum ShapeColor { RED, GREEN, BLUE }; : class Shape { : public: : virtual void draw(ShapeColor color = RED) const = 0; : ... : }; : class Rectangle: public Shape {
| r*******y 发帖数: 1081 | 3 it is interesting. I also write a simple code to check
#include
using namespace std;
class I{
public:
virtual void f(int i = 1){cout << i <
};
class A: public I{
public:
void f(int j = 2){cout << j << endl;}
};
int main(){
I *p = new A;
p->f();
}
For this code, I think the result would have been 2
but in fact it is 1.
【在 G****A 的大作中提到】 : The question is inspired by Item 38 in <>. Given : following code, : ***************** : enum ShapeColor { RED, GREEN, BLUE }; : class Shape { : public: : virtual void draw(ShapeColor color = RED) const = 0; : ... : }; : class Rectangle: public Shape {
|
|