[英]Is it possible to initialize new object in constructor's initialization list and reference it?
Client is the top class of DLL so I need to create and pass new Session object in it's initialization to create requestor and session should be assigned to same Session. 客户端是DLL的顶级类,因此我需要在初始化时创建并传递新的Session对象以创建请求者,并将会话分配给同一Session。 Is it possible?
可能吗?
class Session
{
public:Session() {}
};
class Requestor
{
public: Requestor(const Session& session) {};
};
class Client
{
public:Client()
{
Session newSession;
requestor = Requestor(newSession);
}
private:
Session session;
Requestor requestor;
};
It is possible, but somewhat fragile in that the initialization order depends on the declaration order of the members. 可能,但有些脆弱,因为初始化顺序取决于成员的声明顺序。 Provided these remain as in your example, you can simply do
如果这些仍然与您的示例相同,则您只需
class Client()
{
public:
Client() : requestor(session) // session is implicitly default constructed
{}
private:
Session session;
Requestor requestor;
};
Note: it isn't clear why you are instantiating a local Session
object in your constructor. 注意:尚不清楚为什么要在构造函数中实例化本地
Session
对象。 I am assuming that is a mistake. 我认为那是一个错误。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.