为了账号安全,请及时绑定邮箱和手机立即绑定

c++入门问题

c++入门问题

C++
慕粉18341035298 2016-12-24 07:51:42
#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;}
查看完整描述

2 回答

?
onemoo

TA贡献883条经验 获得超454个赞

所以我觉得很奇怪,你这个代码似乎没有错。

你看,咱们来梳理下整个结构,确保我没有看错:

  • 你先前置声明了 class two,这是为了让后面 class one 的 show 函数能用two引用作参数

  • 后面是 class one 的类定义,但还不能在这里实现 show 函数(因为还没有 class two 的定义)

  • 随后是 class two 的类定义,在其中给 void one::show(two&) 以 friend 权限

  • 最后是 one::show 的实现,其中直接使用 two 的 private 成员 name 是没有问题的啊!

我没看错吧?  你的代码是这样的没错吧?

你确定是正确进行编译了吗?

查看完整回答
反对 回复 2016-12-24
  • 慕粉18341035298
    慕粉18341035298
    在你的编译器上可以通过吗
  • onemoo
    onemoo
    可以,我把你的代码拷过来(除了开头没用的include外),在我这里gcc 6.2可以编译通过。 按照我写的这个结构组织代码,就可以正确地将成员函数声明为friend,没有问题的! 你的编译器或IDE是什么?哪个版本?
  • onemoo
    onemoo
    这个问题解决了吗?
点击展开后面1
?
onemoo

TA贡献883条经验 获得超454个赞

奇怪,乍看没什么问题啊...

class two 中将 one::show(two&) 声明为 friend 了,那么 one::show 应该可以访问 class two 中的 name。

而且 class one 的类定义在 class two 之前,class one 之前也有 class two 的前置声明了,编译应该可以通过的呀!?...

查看完整回答
反对 回复 2016-12-24
  • 2 回答
  • 0 关注
  • 1485 浏览

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信