我有一个有对象向量的类。我需要做什么才能返回其中一个对象并在课堂外进行更改,以保持更改?是否有可能与常规指针?有没有标准的程序? (是的,我的背景是在Java中。)C++返回对象
Q
C++返回对象
2
A
回答
0
如果你有std :: vector,其中A是你的类,你可以返回一个std :: vector :: iterator。
class A {
public: int a;
};
std::vector<A> v = ...;
std::vector<A>::iterator it = v.begin(); // access to the first element
it = v.begin() + 5; // access to the 5-th element (vector can do random access)
// 'it' can now be used elsewhere
it->a = 0; // changes are reflected in the object inside the vector
*it = A(); // changes the object hold by the vector
请注意,如果矢量改变,那么迭代器可能失效!
1
如果矢量持有指向对象的指针,则从矢量(或更准确地说指向的对象)返回的对象之一的任何更改都会影响矢量中的实例。
4
你的问题是有点模糊,但这里有一个例子:
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,他们确实是学习这门语言的唯一好方法。
0
您需要将参考或指针返回给对象。
type &getref(); // "type &" is a reference
type *getptr(); // "type *" is a pointer
调用者将有权访问基础对象。
但是,你需要确保对象不移动(如果一个向量必须增长的话,它可能会产生)。你可能想考虑使用std :: list来代替。
相关问题
- 1. c + +返回对象
- 2. C++类,对象并返回
- 3. 在C++中返回对象
- 4. 返回对象类型C
- 5. C#.NET WebService返回对象
- 6. C++返回一个对象
- 7. C#返回私人对象
- 8. 返回不返回对象
- 9. 返回对象
- 10. .text()返回对象对象
- 11. JSON.stringify返回对象对象
- 12. JSON返回[对象对象]
- 13. AngularFire2返回[对象对象]
- 14. 在C#.NET中使用C++中的COM对象返回对象[]
- 15. 方法返回SBJson Objective-C的对象
- 16. 返回C中的对象(或结构)++
- 17. 目标C:从方法返回对象
- 18. C++返回对象,这可能吗?
- 19. HTTP POST与JSON对象返回c#
- 20. 函数返回“这”对象在C++
- 21. C++获取到返回的对象
- 22. C#的Web API返回对象列表
- 23. 用C++返回当前对象(* this)?
- 24. 将Java对象数组返回给C++
- 25. C#序列化对象只返回ID
- 26. C++返回参考新对象
- 27. C++对象 - 返回一个指针
- 28. C++返回一个对象复制
- 29. C#等待任务组返回对象
- 30. 反序列化返回null对象c#
你指的是stl向量?请提供您想要的伪代码示例。 – sramij 2015-02-23 07:20:10