提问人:JShorthouse 提问时间:12/5/2019 最后编辑:JShorthouse 更新时间:12/6/2019 访问量:236
Vector 中的结构值在按值传递时损坏
Struct Values inside Vector Become Corrupted when Passed by Value
问:
我有以下简单的结构:
struct Wire {
int start_x;
int end_x;
int start_y;
int end_y;
Wire(int sx, int ex, int sy, int ey): start_x(sx), end_x(ex), start_y(sy), end_y(ey) {}
};
我还有以下打印函数,可以从第一项中获取并打印出一些值:std::vector<Wire>
这些函数是相同的,除了一个按值取参数,另一个按引用取参数。
void print_first_wire_value(std::vector<Wire> wires){
std::cout << "(" << wires[0].start_x << ", " << wires[0].start_y << ")" << std::endl;
}
void print_first_wire_reference(std::vector<Wire> &wires){
std::cout << "(" << wires[0].start_x << ", " << wires[0].start_y << ")" << std::endl;
}
我的主函数包括以下代码。
它使用另一个函数用连线对象填充向量。然后,它调用这两个打印函数。
std::vector<Wire> wires = input_to_wires(first_line);
std::cout << "By value: " << std::endl;
print_first_wire_value(wires);
std::cout << "By reference: " << std::endl;
print_first_wire_reference(wires);
我知道第一个start_x和end_x值是 0 和 0。两个打印函数都应打印这些值。但奇怪的是,我反而得到了这个:
By value:
(-543694264, -543694264)
By reference:
(0, 0)
这到底是怎么回事?
最小可重现示例
(请原谅这些看似奇怪的名字,这是解决代码出现后编程挑战的开始)。
day3_lib.h
#pragma once
#include <vector>
#include <string>
struct Wire{
Wire(int sx, int ex, int sy, int ey);
};
std::vector<Wire> populate_wires();
void print_first_wire_value(std::vector<Wire> wires);
void print_first_wire_reference(std::vector<Wire> &wires);
day3_lib.cpp
#include <vector>
#include <sstream>
#include <iostream>
#include <stdexcept>
struct Wire {
int start_x;
int end_x;
int start_y;
int end_y;
Wire(int sx, int ex, int sy, int ey): start_x(sx), end_x(ex), start_y(sy), end_y(ey) {}
};
std::vector<Wire> populate_wires(){
std::vector<Wire> wires;
Wire wire1(0, 0, 1003, 0);
Wire wire2(1003, 0, 1003, -138);
Wire wire3(1003, 0, 662, -138);
wires.push_back(wire1);
wires.push_back(wire2);
wires.push_back(wire3);
return wires;
}
void print_first_wire_value(std::vector<Wire> wires){
std::cout << "(" << wires[0].start_x << ", " << wires[0].start_y << ")" << std::endl;
}
void print_first_wire_reference(std::vector<Wire> &wires){
std::cout << "(" << wires[0].start_x << ", " << wires[0].start_y << ")" << std::endl;
}
第3天.cpp
#include "./day3_lib.h"
#include <fstream>
#include <iostream>
int main(){
std::vector<Wire> wires = populate_wires();
std::cout << "By value: " << std::endl;
print_first_wire_value(wires);
std::cout << "By reference: " << std::endl;
print_first_wire_reference(wires);
}
答: 暂无答案
评论
struct Wire
struct Wire
.cpp
Wire
#include
.cpp