c++ - 重载运算符<<时出错, "cannot overload functions distinguished by return type alone"

标签 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;
};

在文件的后面,我声明 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::ostreamstd::istream(没有 f)来定义这些函数。这些应该自动与 std::ofstream 实例一起工作(因为继承结构),并且也可以与 std::ostringstream 实例一起工作,例如在单元测试中。

关于c++ - 重载运算符<<时出错, "cannot overload functions distinguished by return type alone",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64556634/

相关文章:

c++ - Boost fsm 和 Boost 状态图路径位置

c++ - C++ 中的原始指针管理

c++ - 是否值得在 Linux 上为 nginx 或 haproxy 的多核服务器试验不同的堆分配器

c++ - 重载运算符..出现逻辑错误

c++ - 隐式转换运算符优先级

c++ - 运算符重载的基本规则和惯用法是什么?

c++ - 怀疑用静态常量变量替换宏

c++ - 如何为小数点分隔符和位数调整 std::stod(字符串加倍)

c++ - 如果未在库类中实现,如何重载运算符?

c++ - 友元函数 = 两个不同类的运算符重载