我正在解析两个描述测试的文本文件。为此,我有两个结构来保存测试实例:
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;
};
在文件的后面,我声明 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;
}
但是,编译器给出编译错误:
cannot overload functions distinguished by return type alone
我不明白为什么,因为 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);
^^^^^^^^^^^^^
};
外面:
std::ostream& operator<< (std::ostream& out, const testcase_mat& m) { /* [...]*/ }
^^^^^^^^^^^^^
这些不一致的返回类型和一致的参数类型导致了您的错误。
你应该让所有的返回类型保持一致。
我建议使用 std::ostream
和 std::istream
(没有 f
)来定义这些函数。这些应该自动与 std::ofstream
实例一起工作(因为继承结构),并且也可以与 std::ostringstream
实例一起工作,例如在单元测试中。
关于c++ - 重载运算符<<时出错, "cannot overload functions distinguished by return type alone",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64556634/