以下のコードでは、 class のオブジェクトに渡される引数に基づいて、 kap
(class )の 2 つのオーバーロードされたコンストラクターのいずれかを呼び出すことを意図しています。opacity
material
class opacity{
private:
int mode;
double kap_const;
double kappa_array[10][10];
public:
opacity(double constkap); // picking the constructor sets the mode
opacity(char* Datafile);
double value(double T, double P); // will return a constant or interpolate
};
opacity::opacity(double constkap):mode(1){
kap_const = constkap;
}
opacity::opacity(char* Datafile):mode(2){
// read file into kappa_array...
}
class Matter {
public:
Matter(int i, double k, char* filename); // many more values are actually passed
opacity kap;
int x; // dummy thing
// more variables, call some functions
};
Matter::Matter(int i, double k, char * filename)
:x(k>0? this->kap(x): this->kap(filename) ) {
// ... rest of initialisation
}
ただし、これは機能しません。
test.cpp: In constructor 'Matter::Matter(int, double, char*)':
test.cpp:32:21: error: no match for call to '(opacity) (void*&)'
test.cpp:32:42: error: no match for call to '(opacity) (char*&)'
test.cpp:32:44: error: no matching function for call to 'opacity::opacity()'
test.cpp:32:44: note: candidates are:
test.cpp:20:1: note: opacity::opacity(char*)
test.cpp:20:1: note: candidate expects 1 argument, 0 provided
test.cpp:16:1: note: opacity::opacity(double)
test.cpp:16:1: note: candidate expects 1 argument, 0 provided
test.cpp:4:7: note: opacity::opacity(const opacity&)
test.cpp:4:7: note: candidate expects 1 argument, 0 provided
私が最初に試したのは、
Matter::Matter(int i, double k, char * filename)
:kap(k>0? k: filename) { // use k<0 as a flag to read from filename
// ... rest of initialisation
}
同様の質問で指摘されているように、コンパイル時の理由から「三項演算子の結果は常に同じ型でなければならない」ため、失敗しました(ただし、そこでは説明されていないようです)。
さて、コンストラクターが受け取るべきMatter
引数に基づいてコンストラクターをオーバーロードすることも、洗練されていない解決策になりますkap
が、これは(1)特にMatter
コンストラクターが多くの変数を取り、多くのアクションを実行するため、非常に洗練されていません (したがって、多くのコードがコンストラクターの初期化リストの一部を変更するためだけに複製されます)、(2)異なるコンストラクターを持つkap
別のクラスが使用されている場合、これは手に負えなくなる可能性があります: N c'torsを持つMクラスの場合、1 つはNになります。 ^ Mの組み合わせ...Matter
誰かが提案や回避策を持っていますか? 前もって感謝します!