c++重载++运算符
Program 1:
程序1:
#include <iostream>
using namespace std;
class Test {
float A;
public:
Test(float a)
{
A = a;
}
void operator++(int)
{
A++;
}
void print()
{
cout << A << endl;
}
};
int main()
{
Test T1(10.5F);
T1++;
T1.print();
return 0;
}
Output:
输出:
11.5
Explanation:
说明:
Here, we create a Test class that contains data member A of float type. And, we defined a default constructor and member function print() to print the value of A, also defined member function to overload post-increment operator by passing dummy argument int. Without the dummy argument, the function will be overloaded for the pre-increment operator.
在这里,我们创建一个Test类,其中包含浮点类型的数据成员 A。 并且,我们定义了默认的构造函数和成员函数print()来打印A的值,还定义了成员函数以通过传递哑参数int 重载后递增运算符 。 如果没有dummy参数,则该函数将对pre-increment运算符重载 。
Program 2:
程式2:
#include <iostream>
using namespace std;
class Test {
float A;
public:
Test()
{
A = 0.0F;
}
Test(float a)
{
A = a;
}
void operator++(float)
{
A++;
}
void print()
{
cout << A << endl;
}
};
int main()
{
Test T1(10.5F);
T1++;
T1.print();
return 0;
}
Output:
输出:
main.cpp:17:26: error: postfix ‘void Test::operator++(float)’
must take ‘int’ as its argument
void operator++(float)
^
main.cpp: In function ‘int main()’:
main.cpp:31:7: error: no ‘operator++(int)’ declared for
postfix ‘++’ [-fpermissive]
T1++;
~~^~
Explanation:
说明:
It will generate compilation error, because, to overload post-increment operator, we need to pass int as a dummy argument. Otherwise, it will generate an error.
它将生成编译错误,因为要重载后递增运算符,我们需要将int作为伪参数传递。 否则会产生错误。
Program 3:
程式3:
#include <iostream>
using namespace std;
class Test {
float A;
public:
Test(float a)
{
A = a;
}
void operator<<()
{
cout << A << endl;
}
};
int main()
{
Test T1(10.5F);
T1 << ;
return 0;
}
Output:
输出:
main.cpp:13:21: error: ‘void Test::operator<
Explanation:
It will generate compilation error, because, to overload the "<
翻译自: https://www.includehelp.com/cpp-tutorial/operator-overloading-find-output-programs-set-4.aspx
c++重载++运算符