我有一些这样的代码:
#include <string>
class another_foo
{
public:
another_foo(std::string str)
{
// something
}
private:
// something
};
class foo
{
public:
foo();
private:
another_foo obj;
};
foo::foo() : obj(str) // no `: obj("abcde")`, because it is not that simple in real situation.
{
std::string str = "abcde"; // generate a string using some method. Not that simple in real situation.
// do something
}
我将初始化obj
哪个是foo
. 但是这段代码无法编译。如何在初始化列表中使用构造函数主体中的变量?
AFAIK,唯一的方法是将str
构造函数生成的代码作为另一个函数分离,然后直接在初始化列表中调用该函数。那是...
#include <string>
class another_foo
{
public:
another_foo(std::string str)
{
// something
}
private:
// something
};
class foo
{
public:
foo();
private:
another_foo obj;
// std::string generate_str() // add this
static std::string generate_str() // EDIT: add `static` to avoid using an invalid member
{
return "abcde"; // generate a string using some method. Not that simple in real situation.
}
};
foo::foo() : obj(generate_str()) // Change here
{
// do something
}
但是有没有更好的方法?