gpt4 book ai didi

C++ 返回对象

转载 作者:搜寻专家 更新时间:2023-10-31 00:48:27 25 4
gpt4 key购买 nike

我有一个包含对象 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

FAQ 有一个很好的 section on references .

此外,如果您是 C++ 新手,请不要尝试使用在线资源进行学习。如果你还没有书,you should ,它们确实是学习语言的唯一好方法。

关于C++ 返回对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2659318/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com