在下面的代码中,我的意图是根据传递给 class 对象的参数调用kap
(class )的两个重载构造函数之一: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个类,一个以N结尾^ M组合...Matter
有人会有建议或解决方法吗?提前致谢!