c++重载++运算符_C ++运算符重载| 查找输出程序| 套装4

本文介绍了如何在C++中重载后置递增运算符,通过示例展示需要传递一个哑参数(int)以区别于前置递增运算符,并解释了不传递该参数会导致的编译错误。
摘要由CSDN通过智能技术生成

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 "<





Comments and Discussions

Ad: Are you a blogger? Join our Blogging forum.


翻译自: https://www.includehelp.com/cpp-tutorial/operator-overloading-find-output-programs-set-4.aspx

c++重载++运算符

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值