朋友与类,但不能访问私人成员 [英] friend with class but can't access private members

查看:113
本文介绍了朋友与类,但不能访问私人成员的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

朋友的功能应该能够访问类私有成员吗?
那么我在这里做错了什么?我已经包括我的.h文件与操作符<<我打算和这个班交朋友。

Friend functions should be able to access a class private members right? So what have I done wrong here? I've included my .h file with the operator<< I intent to befriend with the class.

#include <iostream>

using namespace std;
class fun
{
private:
    int a;
    int b;
    int c;


public:
    fun(int a, int b);
    void my_swap();
    int a_func();
    void print();

    friend ostream& operator<<(ostream& out, const fun& fun);
};

ostream& operator<<(ostream& out, fun& fun)
{
    out << "a= " << fun.a << ", b= " << fun.b << std::endl;

    return out;
}


推荐答案

/ p>

In here...

ostream& operator<<(ostream& out, fun& fun)
{
    out << "a= " << fun.a << ", b= " << fun.b << std::endl;

    return out;
}

您需要

ostream& operator<<(ostream& out, const fun& fun)
{
    out << "a= " << fun.a << ", b= " << fun.b << std::endl;

    return out;
}

(我已经被烧伤了很多次;定义的运算符重载与声明不完全匹配,因此它被认为是一个不同的函数。)

(I've been bitten on the bum by this numerous times; the definition of your operator overload doesn't quite match the declaration, so it is thought to be a different function.)

这篇关于朋友与类,但不能访问私人成员的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆