重生废后翻身记txt下载:入门教程:实例详解C 友元3

来源:百度文库 编辑:九乡新闻网 时间:2024/04/29 08:09:37
示例代码如下:

 

#include <iostream>   
using namespace std; 
class Internet; 
 
class Country 

public
    Country() 
    { 
        strcpy(cname,"中国"); 
    } 
    friend class Internet;//友类的声明 
protected
    char cname[30]; 
}; 
class Internet 

public:   
    Internet(char *name,char *address)   
    {   
        strcpy(Internet::name,name);   
        strcpy(Internet::address,address);  
    } 
    void Editcname(Country &temp); 
protected:   
    char name[20]; 
    char address[20]; 
}; 
void Internet::Editcname(Country &temp) 

    strcpy(temp.cname,"中华人民共和国");  

void main() 

    Internet a("中国软件开发实验室","www.cndev-lab.com"); 
    Country b; 
    a.Editcname(b); 
    cin.get(); 
}

  在上面的代码中我们成功的通过Internet类Editcname成员函数操作了Country类的保护成员cname。

  在编程中,我们使用友元的另外一个重要原因是为了方便重载操作符的使用,这些内容我们将在后面的教程着重讨论!