私はそのようないくつかのコードを持っています:
#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
。しかし、このコードはコンパイルされません。初期化リストのコンストラクターの本体で変数を使用するにはどうすればよいですか?
私の知る限り、唯一の方法は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
}
しかし、もっと良い方法はありますか?