nis*_*inn 0 c++ operator-overloading unary-operator friend-function
我使用友元函数重载了预增量运算符.在重载的friend函数中,变量的值显示正确.但是这个值没有显示在显示功能中,为什么呢?
#include <iostream>
using namespace std;
class Rectangle {
public:
int breadth;
public:
void read();
void display();
friend void operator ++(Rectangle r1);
};
void Rectangle::read()
{
cout << "Enter the breadth of the Rectangle: ";
cin >> breadth;
}
void operator++(Rectangle r1)
{
++r1.breadth;
cout<<r1.breadth<<endl; //correct result
}
void Rectangle::display()
{
cout<<breadth<<endl; // not showing pre-incremented value, why ???
}
int main()
{
cout<<"Unary Operator using Friend Function \n";
Rectangle r1;
r1.read();
++r1;
cout << "\n breadth of Rectangle after increment: ";
r1.display();
return 0;
}
Run Code Online (Sandbox Code Playgroud)
您按值operator ++获取Rectangle对象,这意味着它接收其操作数的副本.然后,它尽职地增加副本的breadth成员,将其打印出来,然后在副本结束时丢弃该副本.
您将要通过引用获取参数:
friend void operator ++(Rectangle &r1)
{
++r1.breadth;
}
Run Code Online (Sandbox Code Playgroud)
还要注意,使用成员函数而不是自由函数来重载一元运算符是很常见的.像这样使用,你不会有这个问题:
class Rectangle
{
// ...
public:
void operator++ ()
{
++breadth;
}
// ...
};
Run Code Online (Sandbox Code Playgroud)
一些侧面评论:
operator++返回对其操作数的引用是很常见的,以模仿内置运算符的作用.就像它可以为a做++ ++ i的那样int i,也应该可以++ ++ r为用户定义的类型r做.
实际上,只有当a)你正在编写一个类似于内置类型的类型,或b)你正在编写一个特定于域的语言时,才应该使用运算符重载.增加矩形不是我可以直观地解释的,并且最好作为命名成员函数完成.你怎么知道是++r增加宽度,高度,还是两者,或者将矩形向右移动,还是......?
| 归档时间: |
|
| 查看次数: |
449 次 |
| 最近记录: |