【C++】【一日一練】通過友元訪問或改變類的私有成員【20140508】

題目來源:Beginners Lab Assignments Code Examples

Accessing Private Data Members in C++. This is a flaw in the language


/*
**Description: Accessing Private Data Members in C++
**Date:2014-05-08
**Author:xyq
*/
#include <iostream>
#include <string>
using namespace std;
class Person
{
private:
    string password;
public:
    string name;
                 
    Person(string name, string password)
    {
        this->name = name;
        this->password = password;
    }  
                 
    // 友元函數
    friend void OutputInfo(const Person &p);    
    friend void SetPW(Person &p);
    // 友元類
    friend class Hacker;
};
// 在友元函數中訪問類的私有成員
void OutputInfo(const Person &p)
{
    cout << "name: " << p.name << endl
         << "password: " << p.password << endl;  
}
// 在友元函數中修改類的私有成員
void SetPW(Person &p)
{
    cout << "隨便你想改成什麼密碼,輸入吧~" << endl;
    string pw;
    cin >> pw;
    p.password = pw;
}
// Person的友元類定義
class Hacker
{
private:
    string name;
public:
    Hacker(string n):name(n){   };
    void modifyPW(Person &p);
};
// 通過友元類修改類的私有成員
void Hacker::modifyPW(Person &p)
{
    p.password = "你的密碼被" + name + "改掉了,哈哈!";
}
int main(int argc, char *argv[])
{
    Person p("Adam", "1234567");
    OutputInfo(p);
    cout << endl;
                  
    SetPW(p);
    OutputInfo(p);
    cout << endl;
                 
    Hacker h("CC");
    h.modifyPW(p);
    OutputInfo(p);
    cout << endl;
                 
    return 0;
}


運行結果:

wKiom1NrqNPjIouYAABnqJijEZU547.jpg

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章