c++入门问题

#include<iostream>
#include<algorithm>
#include<iomanip>
#include<cmath>
#include<string.h>
#include<stdlib.h>
#include<sstream>
using namespace std;
class two;
class one{
private :
 string name;
public :
 void show(two &);
 void setOne(){
  string  s;
  name = s;
 }
};
class two{
private :
 string name;
public :
 friend void one::show(two &);
 void setTwo(){
  string  s;
  name = s;
 }
};
void one :: show(two &s){
 cout << s.name << endl;   //编译器报错,无法访问name,这是为什么?
}
int main()
{
 one a;
 two b;
 a.setOne();
 a.show(b);
 b.setTwo();
 return 0;
}


慕粉18341035298
浏览 1490回答 2
2回答

onemoo

所以我觉得很奇怪,你这个代码似乎没有错。你看,咱们来梳理下整个结构,确保我没有看错:你先前置声明了 class two,这是为了让后面 class one 的 show 函数能用two引用作参数后面是 class one 的类定义,但还不能在这里实现 show 函数(因为还没有 class two 的定义)随后是 class two 的类定义,在其中给 void one::show(two&) 以 friend 权限最后是 one::show 的实现,其中直接使用 two 的 private 成员 name 是没有问题的啊!我没看错吧?  你的代码是这样的没错吧?你确定是正确进行编译了吗?

onemoo

奇怪,乍看没什么问题啊...class two 中将 one::show(two&) 声明为 friend 了,那么 one::show 应该可以访问 class two 中的 name。而且 class one 的类定义在 class two 之前,class one 之前也有 class two 的前置声明了,编译应该可以通过的呀!?...
打开App,查看更多内容
随时随地看视频慕课网APP