Mat*_*Mat 6 c++ inheritance constructor
可能它非常简单,但有人可以告诉我如何使用子类'构造函数中计算的参数调用超类'构造函数?这样的事情:
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);
}
Run Code Online (Sandbox Code Playgroud)
//编辑:我编辑了这个例子,以便超类采用两个彼此有关系的参数
如果您无法用单行表达式来表示您的计算,请添加一个静态函数,然后以通常调用超类的构造函数的方式来调用它:
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;
}
};
Run Code Online (Sandbox Code Playgroud)
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;
}
};
Run Code Online (Sandbox Code Playgroud)