过载++运算符
Overload ++ operator
我第一次尝试处理运算符重载,我写了这段代码来重载++运算符,使类变量i
和x
增加一。。它完成了任务,但编译器显示了以下警告:
警告1警告C4620:找不到的"operator++"后缀形式类型"tclass",使用前缀表单c:\users\ahmed\desktop\cppq\cppq.cpp 25
警告2警告C4620:找不到的"operator++"后缀形式类型"tclass",使用前缀表单c:\users\ahmed\desktop\cppq\cppq.cpp 26
这是我的代码:
class tclass{
public:
int i,x;
tclass(int dd,int d){
i=dd;
x=d;
}
tclass operator++(){
i++;
x++;
return *this;
}
};
int main() {
tclass rr(3,3);
rr++;
rr++;
cout<<rr.x<<" "<<rr.i<<endl;
system("pause");
return 0;
}
此语法:
tclass operator++()
用于前缀++
(实际上通常被写成tclass &operator++()
(。为了区分后缀增量,您添加了一个未使用的int
参数:
tclass operator++(int)
此外,请注意前缀增量最好返回tclass &
,因为结果可能在:(++rr).x
之后使用。
再次注意,后缀增量如下所示:
tclass operator++(int)
{
tclass temp = *this;
++*this; // calls prefix operator ++
// or alternatively ::operator++(); it ++*this weirds you out!!
return temp;
}
有两个++ operator
。您定义了一个并使用了另一个。
tclass& operator++(); //prototype for ++r;
tclass operator++(int); //prototype for r++;
后增量和预增量有单独的重载。增加后版本的签名是operator++(int)
,而增加前版本的签名则是operator++()
。
您已经定义了operator++()
,所以您只定义了预注册。但是,在类的实例上使用postincrement,因此编译器告诉它将使用对preincrement函数的调用,因为没有定义postincremetion。
相关文章:
- C++Cast运算符过载
- 如何解决不明确的运算符过载问题?
- 屏幕插入运算符<<的运算符过载问题
- 对C++运算符过载的一些疑问
- C++ #include和运算符<<过载错误
- C++使 ostream 和 istream 运算符过载
- 运算符过载上未解决的外部符号
- 在Cython中损坏的非成员运算符过载(特别是操作员==)
- 通过移动分配从算术运算符过载中返回const值
- 避免对模板运算符过载的隐式参数转换
- 如何为类模板定义非成员运算符过载
- 分配运算符过载:返回void与返回参考参数
- 如何使用运算符过载添加类变量和INT变量
- 打印运算符过载失败
- 运算符 + 过载错误.无法返回对对象的引用
- 类内与类外运算符过载
- 使用许多类型运算符过载时,模棱两可的超载
- C++输入运算符过载">>"
- 一元减去运算符过载C++分段错误
- 运算符过载<<问题