注册 登录
编程论坛 C++教室

关于friend类成员调用问题

生命太短暂 发布于 2020-05-07 19:06, 1809 次点击
程序代码:
  
个人感觉加了friend不是朋友关系而是黑社会大哥与小第关系,好像在说,我是你大哥你的成员就是我的....
现在呢?我想让sub也当大哥,让subd里的b_放在sub里,解解sub想当大哥的隐?怎么做啊?


 #include <iostream>
using namespace std;
class Subd;
class Sub
{
    int a_=6;

public:Sub (){}
Sub(int a):a_(a){}
void output(/*const Subd&cn*/)//加了注释的地方是报错的
{
    cout<<a_<</*cn.b_<<*/endl;
}
int cheng()
{
    return (a_*a_);
}
friend  class Subd;

};
class Subd
{
    int b_=3;

public:
    Subd (){}

void output(  Sub&tn)
{
    cout<<b_<<" "<<tn.a_<<" "<< tn.cheng() <<endl;
} /*friend  class Sub;*/
};
int main()
{  Sub  tex;tex.output();
   Subd tex1;tex1.output(tex);
}   
6 回复
#2
生命太短暂2020-05-07 19:07
只有本站会员才能查看附件,请 登录
#3
rjsp2020-05-07 20:43
incomplete 是 不完全 的意思。

程序代码:
#include <iostream>
using namespace std;

class Subd;

class Sub
{
public:
    void output( const Subd& cn );
private:
    int a_ = 6;

    friend class Subd;
};

class Subd
{
public:
    void output( const Sub& tn )
    {
        cout << tn.a_<< endl;
    }
private:
    int b_ = 3;

    friend class Sub;
};

inline void Sub::output( const Subd& cn )
{
    cout << cn.b_<< endl;
}

int main( void )
{
    Sub tex;
    Subd tex1;

    tex.output( tex1 );
    tex1.output( tex );
}

#4
生命太短暂2020-05-07 22:24
嗯?我问了那么多群都没问出个答案,原来把out put拿出来就可以啦,感谢玩了一大会这串代码,难道是即使给了sub朋友,因为没见过subd这个老大的面,导致subd和sub互相不认识,sub想蹦哒也蹦哒不了?必须让sub和subd见面才行?所以把output写到外面是为了见一次老大的面混个脸熟?这样理解行吗?
#5
生命太短暂2020-05-07 22:37
class不是默认私有的吗?调到后面加个私有关键字有何特殊的意义吗?
程序代码:


class Subd;

class Sub
{
public:
    void output(const Subd& cn );
    int cheng()const
{int ten=(a_*a_);
    return ten ;
}
private:
    int a_ = 6;
friend class Subd;
   
};

class Subd
{
public:
    void output( const Sub& tn )
    {
        cout << tn.a_<< tn.cheng()<<endl;
    }
private:
    int b_ = 3;
friend class Sub;
   
};

inline void Sub::output(const Subd& cn )
{
    cout << cn.b_<< endl;
}

int main( void )
{
    Sub tex;
    Subd tex1;

    tex.output( tex1 );
    tex1.output( tex );
}


#6
rjsp2020-05-07 22:54
当编译
void output(const Subd&cn)//加了注释的地方是报错的
{
    cout<<a_<<cn.b_<<endl;
}
时,因为此时尚不知道 class Subd 的内存布局,所以没法生成任何代码。
class Subd 有没有 b_ 成员不知道,b_ 是个什么类型不知道,b_ 在 class Subd 中的地址偏移不知道,……。
#7
生命太短暂2020-05-07 23:08
非常感谢,理解了感谢耐心指导
1