首页 > 解决方案 > C++ 二进制 '+'; 未找到采用“对”类型的全局运算符

问题描述

在 Main.cpp 为什么可以p3 = p3 + 2;工作但p3 = 2 + p3;给我标题中所述的错误?

对.h

#pragma once
class Pair
{
private:
    int num1, num2;
public:
    Pair();
    Pair(int num1, int num2);
    int get1();
    int get2();
    Pair operator+(const Pair& other);
    Pair operator+(int otherNum);
};

对.cpp

#include "Pair.h"
Pair::Pair() : num1(0), num2(0)
{
}
Pair::Pair(int num1, int num2) : num1(num1), num2(num2)
{
}
int Pair::get1()
{
    return num1;
}
int Pair::get2()
{
    return num2;
}
// Return a new pair that adds the corresponding numbers
Pair Pair::operator+(const Pair& other)
{
    Pair newPair(this->num1, this->num2);
    newPair.num1 += other.num1;
    newPair.num2 += other.num2;
    return newPair;
}
// Return a new pair that adds otherNum to num1 and num2
Pair Pair::operator+(int otherNum)
{
    Pair newPair(this->num1, this->num2);
    newPair.num1 += otherNum;
    newPair.num2 += otherNum;
    return newPair;
}

主文件

#include <iostream>
#include <string>
#include "Pair.h"
using namespace std;
int main()
{
    Pair p1(5, 10);
    Pair p2(1, 2);
    // Outputs 5 and 10
    cout << p1.get1() << " " << p1.get2() << endl;
    // Outputs 1 and 2
    cout << p2.get1() << " " << p2.get2() << endl;
    Pair p3 = p2 + p1;
    // Outputs 6 and 12
    cout << p3.get1() << " " << p3.get2() << endl;

    p3 = p3 + 2;

    // doesn't work
    //p3 = 2 + p3;

    // Outputs 8 and 14
    cout << p3.get1() << " " << p3.get2() << endl;
}

标签: c++

解决方案


您将 operator+ 定义为 Pair 的成员函数。

因此,当您编写p + 2编译器时,就知道您想在对象 p 上应用 +2。

相反,如果你想允许 int + Pair,你需要在你的类之外定义一个运算符:

Pair operator+(const int&, const Pair&);

相似地,

Pair operator+(const Pair&, const int&);

将允许 Pair + int。


推荐阅读