4.1. Object with Function

เราสามารถสร้าง instance จาก class และคัดลอก instance ดังกล่าวเพื่อส่งให้ function ประมวลผลต่อได้ ตัวอย่างโปรแกรม

        #include<iostream>
    using namespace std;
    class Obj{
      public:
        int x;
    };
    void showX_from_outside(Obj a){
        cout<<a.x;
    }
    int main(){
        Obj a;
        a.x=7;
        showX_from_outside(a);
    }

output

Running /home/ubuntu/workspace/code411_pass_obj_to_func.cpp                                               
7

4.2 friend

friend ใส่นำหน้าฟังก์ชัน เมื่อต้องการให้ฟังก์ชันนั้นเข้าถึง private data members หรือ private member functions ภายในคลาส

        #include<iostream>
        #include <string>
        using namespace std;
        //no function prototype is required
        class Man{
            private:
                string hand;
                void isTouch (){ hand+="is touched"; }
                friend void hold(Man);
                friend void touch(Man);
            public:
                Man(){ hand="My hand "; }

        };
        void hold(Man jobs){
            jobs.hand+="is held";
            cout << jobs.hand << endl;
        }
        void touch(Man jobs){
            jobs.isTouch();
            cout << jobs.hand << endl;
        }
        int main(){
            Man jobs;
            hold(jobs);
            touch(jobs);
            return 0;
        }

output

Running /home/ubuntu/workspace/code34_friend.cpp
My hand is held
My hand is touched

results matching ""

    No results matching ""