考慮,我們有兩大類:參數傳遞給家長與參數列表
#include<iostream>
using namespace std;
class Base {
public:
Base(char c) {
cout << __FUNCTION__ <<":"<<__LINE__ << endl;
}
Base(double d) {
cout << __FUNCTION__ <<":"<<__LINE__ << endl;
}
~Base() {
cout << __FUNCTION__ <<":"<<__LINE__ << endl;
}
};
class Derived: public Base{
public:
Derived(int i, float f, char c):Base(c) {
cout << __FUNCTION__ <<":"<<__LINE__ << endl;
}
Derived(int i, float f, double d):Base(d) {
cout << __FUNCTION__ <<":"<<__LINE__ << endl;
}
~Derived() {
cout << __FUNCTION__ <<":"<<__LINE__ << endl;
}
};
這很簡單,易於理解。現在,我們要實現一個新的類DerivedWithParams:
class DerivedWithParams : public Base{
public:
struct Params {
int i;
int f;
char c;
double d;
};
DerivedWithParams(Params* params):Base(params->c) {
cout << __FUNCTION__ <<":"<<__LINE__ << endl;
}
DerivedWithParams(Params* params):Base(params->d) {
cout << __FUNCTION__ <<":"<<__LINE__ << endl;
}
~DerivedWithParams() {
cout << __FUNCTION__ <<":"<<__LINE__ << endl;
}
};
然而,在編譯時,它抱怨: 不能超載
看來C++不支持初始化參數列表超載。任何解決方法?
C++支持重載,但您需要更改簽名。你的兩個構造函數具有相同的簽名。 –
你有兩次'DerivedWithParams(PARAMS * PARAMS)'... – Jarod42
@通過簽名tobi303 - 這包括CV-預選賽。 –