C ++调用具有计算参数的超类构造函数 [英] c++ call superclass constructor with calculated arguments
本文介绍了C ++调用具有计算参数的超类构造函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
这可能超级简单,但是有人可以告诉我如何使用在子类的构造函数中计算出的参数来调用超类的构造函数吗?
probably it's super easy, but can someone tell me how I can call the superclass' constructor with arguments calculated in the subclass' constructor? something like this:
class A{
A(int i, int j);
};
class B : A{
B(int i);
};
B::B(int i){
int complex_calculation_a= i*5;
int complex_calculation_b= i+complex_calculation_a;
A(complex_calculation_a, complex_calculation_b);
}
// edit:我编辑了示例,以便超类接受两个参数彼此有关系
//edit: i edited the example so that the superclass takes two arguments which have a relation to each other
推荐答案
如果无法用单行表达式表示计算,请添加静态函数,然后以通常调用超类的构造函数的方式来调用它:
If you cannot express your calculation in a single-line expression, add a static function, and call it in the way you normally call the constructor of the superclass:
class B : A{
public:
B(int i) : A(calc(i)) {};
private:
static int calc(int i) {
int res = 1;
while (i) {
res *= i--;
}
return res;
}
};
EDIT 多参数情况:
class B : A{
public:
B(int i) : A(calc_a(i), calc_b(i)) {};
private:
static int calc_a(int i) {
int res = 1;
while (i) {
res *= i--;
}
return res;
}
static int calc_b(int i) {
int complex_a = calc_a(i);
return complex_a+10;
}
};
这篇关于C ++调用具有计算参数的超类构造函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文