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编译提示
原因查找
微软文档:
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再次编译