vs2015下重载运算符<operator>C2676:不定义该运算符或到预定义运算符可接收的类型的转换

error C2676: 不定义该运算符或到预定义运算符可接收的类型的转换

源码

#include "stdafx.h"
#include "windows.h"


class numb {
private:
	int lowvalue;
	int highvalue;
public:
	//构造函数
	numb(int lowvalue, int highvalue);
	void print();
    numb operator++();
	numb operator--();
	numb operator-(const numb& p);
	numb operator+(const numb& p);
	numb operator*(const numb& p);
	numb operator/(const numb& p);
	bool operator>(const numb& p);
	bool operator<(const numb& p);
	bool operator==(const numb& p);
};

numb::numb(int lowvalue, int highvalue) {
	this->highvalue = highvalue;
	this->lowvalue = lowvalue;
}
void numb::print() {
	printf("highvalue:%d\nlowvalue:%d\n", this->highvalue, this->lowvalue);

}
numb numb::operator++() {
	lowvalue++;
	highvalue++;
	return *this;
}
numb numb::operator--() {
	lowvalue--;
	highvalue--;
	return *this;
}
numb numb::operator-(const numb& p) {
	this->highvalue = this->highvalue - p.highvalue;
	this->lowvalue = this->lowvalue - p.lowvalue;
	return *this;

}
numb numb::operator+(const numb& p) {
	this->highvalue = this->highvalue + p.highvalue;
	this->lowvalue = this->lowvalue + p.lowvalue;
	return *this;
}
numb numb::operator*(const numb& p) {
	this->highvalue = this->highvalue*p.highvalue;
	this->lowvalue = this->lowvalue*p.lowvalue;
	return *this;
}
numb numb::operator/(const numb& p) {
	this->highvalue = this->highvalue / p.highvalue;
	this->lowvalue = this->lowvalue / p.lowvalue;
	return *this;
}
bool numb::operator>(const numb& p) {
	if (this->highvalue > p.highvalue) {
		return true;
	}
	return false;
}
bool numb::operator<(const numb& p) {
	if (this->highvalue < p.highvalue) {
		return true;

	}
	return false;
}
bool numb::operator==(const numb& p) {
	if (this->highvalue == p.highvalue) {
		return true;
	}
	return false;
}

int main()
{
	int x = 10;
	int y = 5;
	numb n1(x,y);
	n1.print();
	n1++;
	n1.print();
	getchar();
	return 0;
}

用VS2015社区版本编译提示

编译未通过

用VC6编译提示

编译通过了,但是出现警告C4620

原因查找

微软文档:

https://docs.microsoft.com/en-us/cpp/error-messages/compiler-warnings/compiler-warning-level-1-c4620?view=msvc-140
使用前缀形式未找到类型“ type”的“ operator ++”的后缀形式。没有为给定类型定义后缀增量运算符。编译器使用了重载的前缀运算符。

也就是说源码里的

numb operator++();

实际是用于前缀++(++ operator),其默认语法为:

tclass &operator++()

而我们实现的是operator++,要实现后缀增量,添加一个未使用的int参数:

numb operator++(int);
numb numb::operator++(int) {
	lowvalue++;
	highvalue++;
	return *this;
}

VS2015再次编译

编译通过
运行成功

  • 1
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 2
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值