|
|
|
|
|
|
h*c 发帖数: 1859 | 1 【 以下文字转载自 JobHunting 讨论区 】
发信人: woodsmart (pythonip), 信区: JobHunting
标 题: 问个构造函数的问题
发信站: BBS 未名空间站 (Thu Feb 2 18:24:30 2012, 美东)
看神贴看到一道题,想问问有什么好的解法?
Given two classes:
class B
{
public:
B(args_1);
B(args_2);
// and many constructors with different arg lists
};
class D : public B
{
public:
D(args_1) : B(args_1) {}
D(args_2) : B(args_2) {}
// and many constructors with different signatures similarly implemented
// some additional stuff specific to D
};
Assume that the arg list for B's constructors are quite long and may be
revised pretty often in the future, in which case D's constructors have
to be recoded correspondingly. Duplicating the update by copy-and-paste
will certainly work here. Can you propose a better way so that the
update can be done in one place without copy-and-paste duplication? | d****n 发帖数: 1637 | 2 define all parameters in a struct( I googled it.)
//B.h
typedef struct {
int p1,p2,p3,p4,p5.....
} param;
class B{
B(param){
//change param.p1
// change param.p2
// etc.
}
}
//in D.h
#include "B.h"
class D : public B{
D(/*D's private params*/):B( param b){}
};
pros and cons? | p***o 发帖数: 1252 | 3 19643
22398
【在 h*c 的大作中提到】 : 【 以下文字转载自 JobHunting 讨论区 】 : 发信人: woodsmart (pythonip), 信区: JobHunting : 标 题: 问个构造函数的问题 : 发信站: BBS 未名空间站 (Thu Feb 2 18:24:30 2012, 美东) : 看神贴看到一道题,想问问有什么好的解法? : Given two classes: : class B : { : public: : B(args_1);
| t****t 发帖数: 6806 | 4 这你都能找出来啊!
【在 p***o 的大作中提到】 : 19643 : 22398
| t****t 发帖数: 6806 | 5 i guess you are not supposed to change B's ctor, and they are probably not
all int.
the interviewer wanted you to answer templated constructor. but that's an
old question; new answer should be c++11's Inherited Constructor, that is
new [12.9] or N2540. Just write in D's declaration:
using B::B;
That's easy enough.
【在 d****n 的大作中提到】 : define all parameters in a struct( I googled it.) : //B.h : typedef struct { : int p1,p2,p3,p4,p5..... : } param; : class B{ : B(param){ : //change param.p1 : // change param.p2 : // etc.
| p***o 发帖数: 1252 | 6 Just did a title search for 构造 ...
【在 t****t 的大作中提到】 : 这你都能找出来啊!
| p***o 发帖数: 1252 | 7 That's really easy.
【在 t****t 的大作中提到】 : i guess you are not supposed to change B's ctor, and they are probably not : all int. : the interviewer wanted you to answer templated constructor. but that's an : old question; new answer should be c++11's Inherited Constructor, that is : new [12.9] or N2540. Just write in D's declaration: : using B::B; : That's easy enough.
| t****t 发帖数: 6806 | 8 unfortunately, gcc still doesn't support it yet. waiting for 4.8...
【在 p***o 的大作中提到】 : That's really easy.
|
|
|
|
|
|
|