如何使用“Get”分配成员值功能?
这是一个简单的代码。
class Sub
{
...
public:
Sub()
{
...
}
}
class Main
{
private:
Sub* m_pSub
public:
Main()
{
// I don't want construct "Sub" here
m_pSub = nullptr;
}
Sub* GetSub()
{
return m_pSub;
}
}
/////////////////////
// in source
Main* pMain;
pMain->GetSub() = new Sub()
当然,pMain->GetSub() = new Sub()不起作用,因为上面代码中'='的左边值必须是可纠正的值。
因此,请教我各种类似的实施方法 (可以使用尽可能短的)。
谢谢 !
Here's a simple code.
class Sub
{
...
public:
Sub()
{
...
}
}
class Main
{
private:
Sub* m_pSub
public:
Main()
{
// I don't want construct "Sub" here
m_pSub = nullptr;
}
Sub* GetSub()
{
return m_pSub;
}
}
/////////////////////
// in source
Main* pMain;
pMain->GetSub() = new Sub()
Of course, pMain->GetSub() = new Sub() does not work because the left value of '=' in the above code must be a correctable value.
Therefore, please teach me various ways to implement similarly
(which can be used as short as possible).
Thank you !
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
让代码工作的最简单方法是让
GetSub()
返回一个引用,例如:但是,这不是很好的类设计。
另一种选择是让
GetSub()
在第一次调用时创建对象,例如:否则,使用显式 setter 方法,例如:
无论哪种方式,您确实应该使用智能指针,或者
std::unique_ptr
或std::shared_ptr
,以明确谁拥有Sub
对象并负责销毁它。原始指针不传达该信息。The simplest way to make your code work is to have
GetSub()
return a reference, eg:However, this isn't very good class design.
Another option is to have
GetSub()
create the object on its first call, eg:Otherwise, use an explicit setter method, eg:
Either way, you really should be using smart pointers, either
std::unique_ptr
orstd::shared_ptr
, to make it clear who owns theSub
object and is responsible for destroying it. A raw pointer does not convey that information.