所以,如果我有这个:
class Object {
public:
Object(const int id);
~Object();
private:
int o_id;
};
如何返回具有特定o_id(假设为5)的对象?
答案 0 :(得分:3)
您的问题有点令人困惑。在C ++中,函数可以按值或按引用返回对象。当对象通过函数的值返回时。
这可以为您提供帮助:
class Object
{
public:
int value() const
{
return m_value;
}
void setValue( int i )
{
m_value = i;
}
private:
int m_value;
};
答案 1 :(得分:1)
如果我们假设构造函数的定义像这样初始化o_id
Object::Object(const int id) : o_id(id) {}
然后,您只需使用适当的ID调用构造函数即可。
Object an_object(5); // o_id is set to 5