我有一个类有一个std :: vector成员用于存储外部类的对象。C++ - 通过成员函数更改一个类的成员值
class Example {
private:
std::vector<OtherClass> list_of_things_;
}
class OtherClass {
public:
void ChangeName(std::string name);
private:
std::string name_;
}
通过我的代码,我想改变一些存储在此list_of_things_的OtherClass的对象,所以我用我的例子类两种功能:
std::vector<OtherClass> RetrieveObjects() {
std::vector<OtherClass> result;
std::vector<OtherClass>::iterator it;
for (it = list_of_things_.begin(); it != list_of_things_.end(); ++it) {
if (some condition is met) {
result.push_back(*it);
}
}
}
然后在实例中其他功能我打电话这个喜欢:现在
std::vector<OtherClass> objs = RetrieveObjects();
std::vector<OtherClass>::iterator it;
for (it = objs.begin(); it != objs.end(); ++it) {
it->ChangeName("new name");
}
,这是原则上的工作,但只有当我从OBJ文件变量检查名字,这并没有改变内部list_of_things_的对象是我的主要意图。
我真的做了一个对象的副本,而不是检索list_of_things_中的相同对象吗?如果是这样,为什么?我犯了一些其他错误吗?我应该使用指针吗?我是C++新手,仍然在寻找解决方法。
在这里你可以找到一个运行测试代码:
#include <vector>
#include <string>
#include <iostream>
class OtherClass {
public:
OtherClass(std::string s) : name_(s) {}
std::string GetName();
void ChangeName(std::string name);
private:
std::string name_;
};
std::string OtherClass::GetName() {
return name_;
}
void OtherClass::ChangeName(std::string name) {
name_ = name;
}
class Example {
public:
Example(std::vector<OtherClass> l) : list_of_things_(l) {}
void ChangeNames();
void WriteNames();
protected:
std::vector<OtherClass> RetrieveObjects();
private:
std::vector<OtherClass> list_of_things_;
};
std::vector<OtherClass> Example::RetrieveObjects() {
std::vector<OtherClass> result;
std::vector<OtherClass>::iterator it;
for (it = list_of_things_.begin(); it != list_of_things_.end(); ++it) {
if (it->GetName() == "Name") {
result.push_back(*it);
}
}
return result;
}
void Example::ChangeNames() {
std::vector<OtherClass> objs = RetrieveObjects();
std::vector<OtherClass>::iterator it;
for (it = objs.begin(); it != objs.end(); ++it) {
it->ChangeName("new name");
std::cout << it->GetName() << std::endl;
}
}
void Example::WriteNames() {
std::vector<OtherClass>::iterator it;
for (it = list_of_things_.begin(); it != list_of_things_.end(); ++it) {
std::cout << it->GetName() << std::endl;
}
}
int main() {
OtherClass oc = OtherClass("Name");
OtherClass oc2 = OtherClass("None");
OtherClass oc3 = OtherClass("Name");
std::vector<OtherClass> v = {oc, oc2, oc3};
Example ex = Example(v);
ex.ChangeNames();
ex.WriteNames();
}
谢谢!
谢谢你的解释! 如果我想要一个引用向量,我应该使用: std :: vector 与'&'里面? –
EDL
@EDL引用的向量并不真的工作得很好,因为引用是不可变的。在这种情况下,您最好使用指针向量:'std :: vector'。尽管指针在语法上比句柄要复杂得多,所以如果你不熟悉它们,你可能需要先做一些阅读。 –
ComicSansMS