飘云阁

 找回密码
 加入我们

QQ登录

只需一步,快速开始

查看: 1681|回复: 1

[C/C++] 复习下成员/非成员操作符和友元

[复制链接]

该用户从未签到

发表于 2009-9-18 22:49:14 | 显示全部楼层 |阅读模式
//-----------------------------------------------------
// MyAPP.H

class MyApp  
{
//public:
private:
        int Num;
public:
        MyApp(int num);
        virtual ~MyApp();
public:
       
        // 这个其实是 i++ ; i++ == i+1
        // 识记方法:不修改自身 所以需要个参数
        MyApp operator++(int);
        // ++i
        MyApp& operator++();
       
        // 这两个函数说明下成员操作符(省略第一个参数) 和 非成员操作符
        MyApp operator+(int num);
        friend MyApp operator+(int num,const MyApp& obj);
        // 友元输出一下
        friend ostream& operator<<(ostream& o,const MyApp& obj);       
};

//-----------------------------------------------------
// MyAPP.CPP
MyApp::MyApp(int num)
{       
        Num = num;
}

MyApp::~MyApp()
{

}

MyApp MyApp::operator+(int num)
{
        MyApp obj(0);
        obj.Num=Num+num;
        return obj;
}


// 这个其实是 i++
MyApp MyApp::operator++(int num=1)
{
        MyApp temp = * this;
        Num ++;
        return temp;
}

MyApp& MyApp::operator++()
{
        //this->Num ++;
        Num ++;
        return *this;
}

// friend 函数写到CPP好了

MyApp operator+(int num,const MyApp& obj)
{
        MyApp temp(0);
        temp.Num = obj.Num + num;
        return temp;
}

ostream& operator<<(ostream& o,const MyApp& obj)
{
        cout<<obj.Num;
        return o;
}

//-----------------------------------------------------
// Mian.cpp

#include "stdafx.h"
#include "MyApp.h"

// 如果该类的成员不为私有 则可以直接使用 不需要挂带友元
// 如果该类的成员为私有 则友元函数不要写在类之后

// 成员函数只可能带一个参数 MyApp::operator+(int num,const MyApp& obj)
// 这样的话 就不是成员函数了 只能外挂类的函数 或者为友元函数

//  i ++ 参数为(int num=1)      返回为 类类型
//  ++ i 参数为空 以为他不需要         返回为 类的引用

int main(int argc, char* argv[])
{
        MyApp obj(10);
        MyApp obj1 = 5 + obj;
        obj1++;
        cout<<obj1++<<endl;
        ++obj1;
        cout<<++obj1<<endl;
        obj+3;
        3+obj;
        return 0;
}
PYG19周年生日快乐!
  • TA的每日心情
    开心
    2023-8-23 14:44
  • 签到天数: 1 天

    [LV.1]初来乍到

    发表于 2010-1-26 22:08:02 | 显示全部楼层
    /:012  难道我坐了沙发???

    继续抄袭 O(∩_∩)O~
    PYG19周年生日快乐!
    您需要登录后才可以回帖 登录 | 加入我们

    本版积分规则

    快速回复 返回顶部 返回列表