Yak*_*Dan 2 c++ operator-overloading
我正在解析两个描述测试的文本文件。为此,我有两个结构来保存测试实例:
struct testcase_xy {
public:
testcase_xy() = default;
testcase_xy(float x_, float y_, float yaw_, float pitch_) :x(x_), y(y_), yaw(yaw_), pitch(pitch_) {}
friend std::ifstream& operator>> (std::ifstream& in, testcase_xy& t);
friend std::ostream& operator<< (std::ostream& out, const testcase_xy& t);
float x = 0;
float y = 0;
float yaw = 0;
float pitch = 0;
};
struct testcase_mat {
testcase_mat() : pitch(0), yaw(0) { mat.resize(9); }
testcase_mat(float p, float y, std::vector<float> m) : pitch(p), yaw(y), mat(m) {}
friend std::ifstream& operator>> (std::ifstream& in, testcase_mat& m);
friend std::ofstream& operator<< (std::ostream& out, const testcase_mat& m);
float pitch = 0;
float yaw = 0;
std::vector<float> mat;
};
Run Code Online (Sandbox Code Playgroud)
稍后在文件中,我为两个结构声明operator>>并operator<<从文件中读取和输出到std::cout。
std::ifstream& operator>> (std::ifstream& in, testcase_xy& t)
{
in >> t.x >> t.y >> t.yaw >> t.pitch;
return in;
}
std::ostream& operator<< (std::ostream& out, const testcase_xy& t) {
out << "testcase xy x: " << t.x << " y: " << t.y << " yaw: " << " " << t.yaw << " pitch: " << t.pitch << std::endl;
return out;
}
std::ifstream& operator>> (std::ifstream& in, testcase_mat& m)
{
in >> m.pitch >> m.yaw;
float value;
for (int i = 0; i < 9; ++i) {
in >> value;
m.mat.push_back(value);
}
return in;
}
std::ostream& operator<< (std::ostream& out, const testcase_mat& m) {
out << "testcase m: pitch: " << m.pitch << " yaw: " << m.yaw << std::endl;
for (int i = 0; i < 9; ++i)
out << m.mat[i] << std::endl;
return out;
}
Run Code Online (Sandbox Code Playgroud)
但是,编译器给出了一个编译错误:
不能重载仅按返回类型区分的函数
我不明白为什么,因为我为每个结构重载的operator>>和operator<<那个有不同的参数类型,因为结构是不同的类型。
这是怎么回事?
内部结构:
struct testcase_mat {
// [...]
friend std::ifstream& operator>> (std::ifstream& in, testcase_mat& m);
friend std::ofstream& operator<< (std::ostream& out, const testcase_mat& m);
^^^^^^^^^^^^^
};
Run Code Online (Sandbox Code Playgroud)
外部:
std::ostream& operator<< (std::ostream& out, const testcase_mat& m) { /* [...]*/ }
^^^^^^^^^^^^^
Run Code Online (Sandbox Code Playgroud)
这些不一致的返回类型和一致的参数类型会导致您的错误。
您应该使所有返回类型一致。
我建议使用std::ostream和std::istream(不带f)来定义这些函数。这些应该自动与std::ofstream实例一起工作(因为继承结构),并且也将与std::ostringstream实例一起工作,例如在单元测试中。