c++ - 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;
}
解决方案
您将 operator+ 定义为 Pair 的成员函数。
因此,当您编写p + 2
编译器时,就知道您想在对象 p 上应用 +2。
相反,如果你想允许 int + Pair,你需要在你的类之外定义一个运算符:
Pair operator+(const int&, const Pair&);
相似地,
Pair operator+(const Pair&, const int&);
将允许 Pair + int。
推荐阅读
- shopify - 突出显示 shopify 中的活动收藏按钮
- c# - 在接口内部的上下文中,“新”运算符是什么意思?
- ios - 更改 Xcode 11 后未找到架构 x86_64 的符号
- java - System.err.print(ln) 与 system.out.println 在同一行吗?JAVA
- python - 把Python的输入函数变成C
- reactjs - 除了异步操作之外,redux 中的“副作用”究竟是什么?
- swift - 当我物理更新我的 Firestore 数据库字段时,我的应用程序无法访问这些新字段,并显示旧字段
- tkinter - tkinter 的文件对话框询问打开文件名无法显示文件系统
- r - 如何按组查找滚动列中的前 3 个值?
- c# - 创建视图后未将对象引用设置为对象的实例