2010-04-17 114 views
2

我有一个有对象向量的类。我需要做什么才能返回其中一个对象并在课堂外进行更改,以保持更改?是否有可能与常规指针?有没有标准的程序? (是的,我的背景是在Java中。)C++返回对象

+0

你指的是stl向量?请提供您想要的伪代码示例。 – sramij 2015-02-23 07:20:10

回答

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

+1,但您可能想要显示vec的声明以增加清晰度。 – Cam 2010-04-17 17:50:58

+0

@incrediman:除非我误解,否则它在班级的私人部分。 – GManNickG 2010-04-17 17:54:56

+2

您应该强调有关返回参考的详细信息。对于刚接触这门语言的人来说,这可能并不明显,这是“魔术”。 – 2010-04-17 17:59:28

0

您需要将参考指针返回给对象。

type &getref(); // "type &" is a reference 
type *getptr(); // "type *" is a pointer 

调用者将有权访问基础对象。

但是,你需要确保对象不移动(如果一个向量必须增长的话,它可能会产生)。你可能想考虑使用std :: list来代替。