我一直在为学校工作,我们必须创建一个 Client 类,其中包含 4 个字符串、4 个 int 和一个 vector(int) 作为最后一个参数。问题是,当我想打印 vector 的所有元素时,如果我直接使用我的增变器,它会打印出无意义的内容。
vector<int> v_int;
vector<int>::iterator it_v_i;
v_int.push_back(2);
v_int.push_back(3);
v_int.push_back(7);
v_int.push_back(1);
Client client("nom1", "prenom1", "adress1", "city1", "comment1", 1240967102, 44522, 5, 10, v_int);
v_int = client.getIdResources();
for (it_v_i = v_int.begin(); it_v_i != v_int.end(); it_v_i++) {
cout << *it_v_i << ", ";
}
按预期打印 2,3,7,1,但是下面的代码
for (it_v_i = client.getIdResources().begin(); it_v_i != client.getIdResources().end(); it_v_i++) {
cout << *it_v_i << ", ";
}
打印不明号码(如3417664...),不明号码,7, 1
我真的不明白为什么会这样
编辑:
构造函数:
Client::Client(const string& name, const string& surname, const string& adress, const string& city, const string& comment,
const int& phoneNb, const int& postalCode, const int& termAppointment, const int& priority, const vector<int>& idResources)
: name(name), surname(surname), adress(adress), city(city), comment(comment), phoneNumber(phoneNb),
postalCode(postalCode), termAppointment(termAppointment), priority(priority), idResources(idResources)
{
突变体:
std::vector<int> getIdResources() const{ return idResources; }
最佳答案
问题是在第二个片段中 两个 临时 vector
s 用于获取 begin()
和 end()
迭代器(假设声明是 std::vector<int> client.getIdResources()
而不是 std::vector<int>& client.getIdResources()
)。这意味着 it_v_i
指的是被破坏的元素 std::vector
.当it_v_i
被取消引用会导致未定义的行为。
要使第二个代码片段正常运行,请引用 std::vector
需要由 client.getIdResources()
返回.但是,返回对内部类成员的引用会引入其他问题,例如生命周期问题。
关于C++ 奇怪的行为变异 vector ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22222635/