我有一个包含对象 vector 的类。我需要做什么才能返回该对象之一并在类之外更改它并保留更改?可以用常规指针来做吗?有标准程序吗? (是的,我的背景是 Java。)
最佳答案
你的问题有点模糊,但这里有一个例子:
class foo
{
public:
foo()
{
vec.resize(100);
}
// normally would be operator[]
int& get(size_t pIndex)
{ // the return type is a reference. think of it as an alias
return vec[pIndex]; // now the return value is an alias to this value
}
private:
std::vector<int> vec;
};
foo f;
f.get(10) = 5;
// f.get(10) returned an alias to f.vec[10], so this is equivalent to
// f.vec[10] = 5
常见问题解答有一个很好的section on references .
此外,如果您是 C++ 新手,请不要尝试使用在线资源进行学习。如果你还没有书,you should ,它们确实是学习语言的唯一好方法。
关于C++ 返回对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2659318/