假设我有一个看起来像这样的类
class MyAnimals{
public:
Animal getAnimal(int index){
return animals.at(index);
}
private:
vector<Animal> animals;
}
根据我目前对 C++ 的了解,我认为 getAnimal
目前返回动物的拷贝,而不是像 Java 中那样的引用。我已经将此建议作为返回对象的正确方法,但是如果您想要在返回该动物后对其进行修改怎么办?我只是更改它的拷贝,而 MyAnimals.animals 中的实际动物将保持不变。我看到解决这个问题的一种方法是返回 Animal&
而不是 Animal
,这似乎在大多数情况下都有效,但是如果我想重新分配变量被分配给返回的动物?例如,
Animal& a = myanimals.getAnimal(1);
a = myanimals.getAnimal(2);
据我所知,这会将 myanimals.animals[1]
中的动物更改为与 myanimals.animals[2]
完全相同的对象,因为是一个引用。返回对象有哪些不同的方法?
最佳答案
From what I've learned about C++ so far, I think getAnimal currently returns a copy of the animal, not a reference like in Java.
正确。
I've seen this suggested as the correct way to go about returning objects
如果您打算退还拷贝,可以。
I'd just be changing the copy of it and the actual animal inside of MyAnimals.animals would remain unchanged.
正确。
One way I've seen to get around this is to return Animal& instead of Animal, and that seems to work for the most part
是的,引用正是您所需要的。
but what if I want to reassign the variable the was assigned to that returned Animal?
好吧,通常不需要重新分配现有的引用(无论如何都是不允许的)。除了您所做的,您还可以:
Animal& a = myanimals.getAnimal(1);
Animal& b = myanimals.getAnimal(2);
如果出于某种原因需要,请改用指针来绕过限制。即使在返回引用时也可以这样做:
Animal* a = &myanimals.getAnimal(1);
a = &myanimals.getAnimal(2);
关于c++ - 在 C++ 方法中返回对象的方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32743135/