首页 > 代码库 > 【C++】【一日一练】通过友元访问或改变类的私有成员【20140508】

【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

本文出自 “有梦为马” 博客,请务必保留此出处http://adamcc.blog.51cto.com/6605324/1408661