c++ friend声明友元函数后,仍然无法访问类的私有数据;friend友元函数的使用

 错误原因:

一、友元函数friend拼写错误(frined),或者写在类的外面

//friend void Other::Get_secret(People &ob);

class People
{
    //frined void Other::Get_secret(People &ob);
    friend void Other::Get_secret(People &ob);
private:
    char bust;
public:
    string name;
    int age;
    People(){}
};

二、类的成员函数,作为另一个类的友元

People类中私有数据bust,

Other类中的Ger_secret()函数想访问People类中的私有数据

将成员函数Get_secret()函数设为People类的友元

 错误解决方式:

1.开头要向前申明  class People 的存在

2.友元函数所在的Other类写在最前面

3.Other类中的作为友元的成员函数,写在类的外面(具体得在People类的后面)

4.将Other类中的成员函数,写入People类中作为友元函数

#include<iostream>
#include<string>
using namespace std;

class People;//1. 向前声明,只能说明类的名称
class Other   //2.友元成员函数所在类放在最上面
{
public:
    void Get_secret(People &ob);   //2.让这里的People可以是识别到
};


class People
{
    friend void Other::Get_secret(People &ob);     //4
private:
    char bust;
public:
    string name;
    int age;
    People(char bust,string name,int age){
        this->bust = bust;
        this->name = name;
        this->age = age;
    }

};

//3. 成员函数写在类外面
void Other::Get_secret(People &ob){
    cout<<"你好,你是:"<<ob.name<<" "<<"你的年龄是:"<<ob.age<<endl;
    cout<<"your bust is:"<<ob.bust<<endl;
}

int main()
{
    People lucy('A',"lucy",18);   //初始化lucy
    Other Tom;                    //Tom去访问lucy,包括lucy的私有数据
    Tom.Get_secret(lucy);

    return 0;
}

 解释

1.程序自上而下运行,如果不声明class People,那么other类函数Get_secret(People &ob)中People将无法被识别。

2.如果将People类写在最上面,Other类写在下面,那么将导致People类友元函数other类无法识别,即使前面声明class Other ,程序也找不到Get_secret成员(自上而下运行)。

3.Get_secret成员函数若写在Other类的里面,程序自上而下运行,代码中声明了存在People这个类,程序并不知道类中有哪些数据成员,报错。

三、整个类作为另一个类的友元

开头只需声明即可,作为友元的类位置任意,并且成员函数可写在类里面

#include<iostream>
#include<string>
using namespace std;

class Other;//1. 向前声明,只能说明类的名称


class People
{
    friend class Other;  
private:
    char bust;
public:
    string name;
    int age;
    People(char bust,string name,int age){
        this->bust = bust;
        this->name = name;
        this->age = age;
    }

};

class Other  
{
public:
    void Get_secret(People &ob);   

};

void Other::Get_secret(People &ob){
    cout<<"你好,你是:"<<ob.name<<" "<<"你的年龄是:"<<ob.age<<endl;
    cout<<"your bust is:"<<ob.bust<<endl;
}

int main()
{
    People lucy('A',"lucy",18);   //初始化lucy
    Other Tom;                    //Tom去访问lucy,包括lucy的私有数据
    Tom.Get_secret(lucy);
    return 0;
}

猜你喜欢

转载自blog.csdn.net/weixin_46290752/article/details/128552650
今日推荐