我在基类构造函数中有一个逻辑。必须在派生类构造函数中的临时变量中捕获逻辑的结果。有办法吗?
例如
class Base
{
Base() { int temp_value = some_logic; }
};
class Derived : public Base
{
Derived() { // need the temp value here.. }
};
谢谢, 戈库尔。
答案 0 :(得分:2)
我想我能想到的最简单的方法就是将some_logic分成它自己的方法......
class Base
{
Base() { int temp_value = initializationLogic(); }
int initializationLogic(){ return some-logic;}
};
class Derived : public Base
{
Derived() { int temp_value_here_too = initializationLogic(); }
};
答案 1 :(得分:2)
或者:
class Base
{
protected int not_so_temp_value;
Base() { not_so_temp_value = some_logic_result; }
};
class Derived : public Base
{
Derived() { // read the not_so_temp_value member here.. }
};
或者:
class Base
{
Base(int some_logic_result) { int temp_value = some_logic; }
};
class Derived : public Base
{
static Derived* create()
{
int some_logic_result = some_logic;
return new Derived(some_logic_result);
}
Derived(int some_logic_result) : Base(some_logic_result)
{ // use the some_logic_result here.. }
};
答案 2 :(得分:0)
这是我打算使用的那个
class Base
{
Base(int& some_logic_result) { some_logic_result = some_logic; }
};
class Derived : public Base
{
Derived(int some_logic_result = 0) : Base(some_logic_result)
{ // use the some_logic_result here.. }
};
谢谢, 戈库尔。