成都创新互联网站制作重庆分公司

怎么在C++中实现一个友元类-创新互联

这期内容当中小编将会给大家带来有关怎么在C++中实现一个友元类,文章内容丰富且以专业的角度为大家分析和叙述,阅读完这篇文章希望大家可以有所收获。

创新互联是一家专注于成都网站设计、成都做网站与策划设计,猇亭网站建设哪家好?创新互联做网站,专注于网站建设10余年,网设计领域的专业建站公司;建站业务涵盖:猇亭等地区。猇亭做网站价格咨询:13518219792

C++中的友元既可以实现友元函数,也可以实现友元类,也就是说一个类也可以作为另外一个类的友元。当作为一个类的友元时,它的所有成员函数都是另一个类的友元函数,都可以访问另一个类的私有或者公有成员。

#include 
#include 
using namespace std ;
//声明教师类 
class Techer ;
//学生类 
class Student 
{
 private:
 string name ;
 int age ; 
 char sex ; 
 int score ; 
 public :
 Student(string name , int age , char sex , int score);
 void stu_print(Techer &tech);
};
//教师类 
class Techer
{
 private:
 string name ;
 int age ; 
 char sex ; 
 int score ; 
 public :
 Techer(string name , int age , char sex , int score);
 //声明一个友元类
 friend Student ;
};
//Student类的构造函数的实现 
Student::Student(string name , int age , char sex , int score)
{
 this->name = name ; 
 this->age = age ; 
 this->sex = sex ; 
 this->score = score ;
}
//Techer类的构造函数的实现
Techer::Techer(string name , int age , char sex , int score)
{
 this->name = name ; 
 this->age = age ; 
 this->sex = sex ; 
 this->score = score ;
}
//打印Student类中的私有成员和Techer的私有成员 
void Student::stu_print(Techer &tech)
{
 //用this指针访问本类的成员 
 cout << this->name << endl ; 
 cout << this->age << endl ; 
 cout << this->sex << endl ; 
 cout << this->score << endl ;
 //访问Techer类的成员 
 cout << tech.name << endl ;
 cout << tech.age << endl ; 
 cout << tech.sex << endl ; 
 cout << tech.score << endl ;
}
int main(void)
{
 Student stu1("YYX",24,'N',86);
 Techer t1("hou",40,'N',99);
 stu1.stu_print(t1);
 return 0 ;
}

运行结果:

YYX
24
N
86
hou
40
N
99

上述就是小编为大家分享的怎么在C++中实现一个友元类了,如果刚好有类似的疑惑,不妨参照上述分析进行理解。如果想知道更多相关知识,欢迎关注创新互联网站建设公司行业资讯频道。

另外有需要云服务器可以了解下创新互联建站www.cdcxhl.com,海内外云服务器15元起步,三天无理由+7*72小时售后在线,公司持有idc许可证,提供“云服务器、裸金属服务器、高防服务器、香港服务器、美国服务器、虚拟主机、免备案服务器”等云主机租用服务以及企业上云的综合解决方案,具有“安全稳定、简单易用、服务可用性高、性价比高”等特点与优势,专为企业上云打造定制,能够满足用户丰富、多元化的应用场景需求。


名称栏目:怎么在C++中实现一个友元类-创新互联
标题链接:http://cxhlcq.com/article/dhjdho.html

其他资讯

在线咨询

微信咨询

电话咨询

028-86922220(工作日)

18980820575(7×24)

提交需求

返回顶部