1、友元函數ios
#include<iostream> using namespace std; class Student{ private: int id; string name; public: Student(int id,string name); //聲明友元函數 friend void show(Student &stu); }; //友元函數的實現(直接能夠訪問類的私有屬性) void show(Student &stu){ cout<< stu.id << " name:" <<stu.name <<endl; }; Student::Student(int id,string name):id(id),name(name){ } int main(){ Student stu(1,"張三"); show(stu); return 0; }
#include<iostream> using namespace std; class Teacher; class Student{ private: int id; string name; public: Student(int id,string name); void show(Teacher *tea); }; Student::Student(int id,string name):id(id),name(name){ } class Teacher{ private: int id; string name; public: Teacher(int id,string name); //將Student類聲明爲Teacher類的友元類 friend class Student; }; Teacher::Teacher(int id,string name):id(id),name(name){ } void Student::show(Teacher *tea){ cout << this->id << this->name << tea->name << endl; } int main(){ Teacher tea(1,"老外"); Student stu(1,"張三"); stu.show(&tea); return 0; }