您的位置:首页 > 编程语言 > C语言/C++

C++友元函数神奇的friend

2017-03-05 10:33 169 查看
在类中将普通的函数声明为友元函数,即可以使用该友元函数对类中的私有成员进行访问

#include <iostream>

using namespace std;

class Time{
public:
Time(int,int,int);
friend void display(Time &);
private:
int  hour;
int  minute;
int sec;

};
Time::Time(int h, int m, int s) {    //定义一个构造函数并对构造函数
hour=h;
minute=m;
sec=s;

}
void display(Time &a)
{
cout<<a.hour<<":"<<a.minute<<":"<<a.sec<<endl;

}

int main()
{
Time t1(10,13,56);
display(t1);    //display函数可以使用对象成员中的私有数据成员
return 0;
}


**/home/andrew/文档/Clion/untitled5/cmake-build-debug/untitled5
10:13:56

Process finished with exit code 0
**


将另一个类中的成员函数声明为友元函数

**#include <iostream>

using namespace std;
class Date;  //对Date类进行提前声明
class Time{
public:
Time(int,int,int);
void display(Date &);
private:
int  hour;
int  minute;
int sec;

};
class Date{
public:
Date(int,int,int);
friend void Time::display(Date &);    //声明Time类中的display函数为本类中的友元函数
private:
int month;
int day;
int year;

};
Time::Time(int h, int m, int s) {    //定义一个构造函数并对构造函数
hour=h;
minute=m;
sec=s;

}
void Time::display(Date &d) {
cout<<d.month<<"/"<<d.day<<"/"<<d.year<<endl;    //Time中的成员函数引用Date类中的私有成员数据
cout<<hour<<":"<<minute<<":"<<sec<<endl;

}
Date::Date(int m, int d, int y) {
month=m;
day=d;
year=y;

}
int main()
{
Time t1(10,13,56);
Date d1(12,25,2004);
t1.display(d1);
return 0;
}

**


类可以提前声明,但是必须在正式定义之后才能够使用类进行定义,类的对象。

**#include <iostream>

using namespace std;
class Date;  //对Date类进行提前声明,虽进行了提前声明,但是类只有在进行了定义之后才能够使用
//Date t3(10,12,15);    //声明之后直接使用类,编译出错,因为类可以提前声明,但是作用范围有限,类只有正式定义之后才能够使用类去定义一个类型
class Time{
public:
Time(int,int,int);
void display(Date &);
private:
int  hour;
int  minute;
int sec;

};
class Date{
public:
Date(int,int,int);
friend void Time::display(Date &);    //声明Time类中的display函数为本类中的友元函数
private:
int month;
int day;
int year;

};
Time::Time(int h, int m, int s) {    //定义一个构造函数并对构造函数
hour=h;
minute=m;
sec=s;

}
void Time::display(Date &d) {
cout<<d.month<<"/"<<d.day<<"/"<<d.year<<endl;    //Time中的成员函数引用Date类中的私有成员数据
cout<<hour<<":"<<minute<<":"<<sec<<endl;

}
Date::Date(int m, int d, int y) {
month=m;
day=d;
year=y;

}
int main()
{
Time t1(10,13,56);
Date d1(12,25,2004);
t1.display(d1);
return 0;
}

**


**/home/andrew/D/clion/bin/cmake/bin/cmake --build /home/andrew/文档/Clion/untitled5/cmake-build-debug --target untitled5 -- -j 8
Scanning dependencies of target untitled5
[ 50%] Building CXX object CMakeFiles/untitled5.dir/main.cpp.o
/home/andrew/文档/Clion/untitled5/main.cpp:5:8: error: variable ‘Date t3’ has initializer but incomplete type
Date t3(10,12,15);
^
make[3]: *** [CMakeFiles/untitled5.dir/main.cpp.o] 错误 1
make[2]: *** [CMakeFiles/untitled5.dir/all] 错误 2
make[1]: *** [CMakeFiles/untitled5.dir/rule] 错误 2
make: *** [untitled5] 错误 2
**
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: