C++重载函数运算符的两种定义方法(类中|类外(友元))

C++中重载运算符函数的方式:

以重载‘-’号为例,自定义为乘法。

第一种是直接在类内声明定义:(返回值是本类的对象)

#include <iostream>
using namespace std;
class test
{
public:
    test() {}
    test(int t1)
    {
        item = t1;
    }
    test operator-(test &t2)
    {
        this->item = this->item*t2.item;
        return *this;
    }
    void show()
    {
        cout << this->item;
    }

private:
    int item;
};
int main()
{
    test t1(10);
    test t2(20);
    test t3 = t1 - t2;
    t3.show();
    system("pause");
    return 0;
}

第二种是在类中声明为友元函数,类外定义,返回值的是一个类的对象。

#include <iostream>
using namespace std;
class test
{
public:
    test() {}
    test(int t1)
    {
        item = t1;
    }
    void show()
    {
        cout << this->item;
    }
    friend test operator-(test &t1, test &t2);         
private:
    int item;
};
test operator-(test &t1, test &t2)
{
    test t;
    t.item = t1.item*t2.item;
    return t;
}
int main()
{
    test t1(10);
    test t2(20);
    test t3 = t1 - t2;
    t3.show();
    system("pause");
    return 0;
}

猜你喜欢

转载自www.cnblogs.com/god-for-speed/p/10941044.html
今日推荐