#include<iostream> using namespace std; class girl { private: char name; int age; public: girl(char n, int d) //构造函数 { name= n; age=d; } void display(girl &x); //声明友元函数 }; void display() //类外定义 友元函数 { cout<<"Girl's name is :"<<x. name<<", age is :"<<x.age<<endl; //girl类的友元函数能访问girl类对象的私有成员 } int main( ) { girl e('z',18); display( e ); //调用友元函数 return 0; }
时间: 2024-03-18 14:40:38 浏览: 15
该程序有错误,编译时会提示错误信息。具体来说,在类外定义友元函数`display`时,应该传入`girl`类型的引用参数,而不是空参数列表。修改后的程序如下:
```
#include<iostream>
using namespace std;
class girl {
private:
char name;
int age;
public:
girl(char n, int d) { //构造函数
name = n;
age = d;
}
friend void display(girl &x); //声明友元函数
};
void display(girl &x) { //类外定义友元函数
cout<<"Girl's name is :"<<x.name<<", age is :"<<x.age<<endl;
//girl类的友元函数能访问girl类对象的私有成员
}
int main() {
girl e('z', 18);
display(e); //调用友元函数
return 0;
}
```
相关问题
#include<iostream> #include<cstdio> using namespace std;是什么意思
#include<iostream> #include<cstdio> using namespace std; 是C++中的预处理指令,用于引入头文件和命名空间。
1. #include<iostream> 是引入iostream头文件,其中包含了输入输出流的定义,例如cout和cin等。
2. #include<cstdio> 是引入cstdio头文件,其中包含了C语言标准输入输出函数的定义,例如printf和scanf等。
3. using namespace std; 是使用std命名空间,std是C++标准库的命名空间,其中包含了很多常用的函数和类。
这些预处理指令的作用是为了在程序中能够使用输入输出流和标准库函数,使得程序更加方便和简洁。
#include<iostream>using namespace std;
这是一个C++的代码片段,它包含了iostream头文件和使用了命名空间std。iostream头文件提供了输入输出流的功能,而using namespace std;语句则是为了方便使用std命名空间中的函数和对象,避免每次都需要写std::。
以下是一个简单的示例代码,展示了如何使用iostream头文件和命名空间std来输出一句话:
```cpp
#include <iostream>
using namespace std;
int main() {
cout << "Hello, World!" << endl;
return 0;
}
```
这段代码会输出"Hello, World!",endl是一个特殊的控制符,用于在输出流中插入一个换行符。
相关推荐
![text/plain](https://img-home.csdnimg.cn/images/20210720083646.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)