【发布时间】:2008-12-17 16:31:16
【问题描述】:
我正在尝试实现这样的目标:
class Base
{
public:
Base(string S)
{
...
};
}
class Derived: Base
{
public:
int foo;
string bar()
{
return stringof(foo); // actually, something more complex
};
Derived(int f) : foo(f), Base(bar())
{
};
}
现在,这不能如我所愿,因为 bar() 在 foo 初始化之前在 Derived 构造函数中被调用。
我考虑添加一个类似于 bar() 的静态函数,它以 foo 作为参数 - 并在初始化列表中使用它,但我想我会问是否有任何其他技术可以用来让自己摆脱困境这个……
编辑:感谢您的反馈 - 这是我将如何处理静态函数的方法。不确定静态和非静态函数之间的重载是否太聪明了,但是...
class Derived: Base
{
public:
int foo;
static string bar(int f)
{
return stringof(f); // actually, something more complex
}
string bar()
{
return bar(foo);
};
Derived(int f) : Base(bar(f)) , foo(f)
{
};
}
【问题讨论】:
标签: c++ inheritance constructor initialization composition