zoukankan      html  css  js  c++  java
  • c++中友元机制

    友元的概念:遵循一定规则而使对象以外的软件系统能够不经过消息传递方式而直接访问对象内封装的数据成员的技术方法便是友元。

    只要将外界的某个对象说明为一个类的友元,那么这个外界对象就可以访问这个类对象中的私有成员。

    声明为友元的外界对象既可以是另一个类的成员函数,也可以是不属于任何类的一般函数,还可以是整个类(这样,此类中的所有成员函数都成为友元函数)。

    1.友元函数

    先来一段代码,让大家看看友元函数的用法吧!

    #define strmax 32
    #include<iostream>
    #include<string>
    using namespace std;
    class myclass
    {
        int x,y;
        char *string;
    public:
        myclass(int vx,int vy,char *str){
                x=vx;
        y=vy;
        string=new char[strmax];
        strcpy(string,str);
        }
        //friend int sum(myclass c1);
    };
    int sum(myclass c1)
    {
        return c1.x+c1.y;
    }
    int main()
    {
        myclass c1(10,10,"my myclass object!");
        cout<<"the sum is:"<<sum(c1)<<endl;
    
    
        return 0;
    
    }

    编译结果如下:

    Compiling...
    friend1.cpp
    F:c++friend1.cpp(20) : error C2248: 'x' : cannot access private member declared in class 'myclass'
    F:c++friend1.cpp(7) : see declaration of 'x'
    F:c++friend1.cpp(20) : error C2248: 'y' : cannot access private member declared in class 'myclass'
    F:c++friend1.cpp(7) : see declaration of 'y'
    Error executing cl.exe.

    friend1.exe - 2 error(s), 0 warning(s)

    由于对象访问了private成员变量,因此编译会失败!

    现在去掉注释,代码如下:

    #define strmax 32
    #include<iostream>
    #include<string>
    using namespace std;
    class myclass
    {
        int x,y;
        char *string;
    public:
        myclass(int vx,int vy,char *str){
                x=vx;
        y=vy;
        string=new char[strmax];
        strcpy(string,str);
        }
        friend int sum(myclass c1);
    };
    int sum(myclass c1)
    {
        return c1.x+c1.y;
    }
    int main()
    {
        myclass c1(10,10,"my myclass object!");
        cout<<"the sum is:"<<sum(c1)<<endl;
    
    
        return 0;
    
    }

    编译通过,而且结果为the sum is:20

     2.友元成员

    另一个类的成员函数作为某个类的友元,只是在声明友元函数时要加上成员函数所在的类名,称为友元函数。

    3.友元类

    某个类可以是另一个类的友元,这样作为友元的类中的所有成员函数都可以访问声明其为友元类的类中的全部成员。

  • 相关阅读:
    EntityFramework 启用迁移 EnableMigrations 报异常 "No context type was found in the assembly"
    JAVA 访问FTP服务器示例(2)
    NuGet Package Manager 更新错误解决办法
    JAVA 访问FTP服务器示例(1)
    RemoteAttribute 的使用问题
    诡异的 javascript 变量
    javascript apply用法
    Babun 中文乱码
    GSM呼叫过程
    转站博客园
  • 原文地址:https://www.cnblogs.com/liujunming/p/4540918.html
Copyright © 2011-2022 走看看