gpt4 book ai didi

c++ - 有类(class)的 friend 但不能访问私有(private)成员

转载 作者:可可西里 更新时间:2023-11-01 15:46:00 25 4
gpt4 key购买 nike

友元函数应该可以访问一个类的私有(private)成员吧?那么我在这里做错了什么?我已经将我的 .h 文件包含在运算符<<我打算与类(class)交 friend 。

#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;
}

最佳答案

在这里...

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;
}

(我被这件事折磨了无数次;你的运算符重载的定义与声明不完全匹配,所以它被认为是一个不同的函数。)

关于c++ - 有类(class)的 friend 但不能访问私有(private)成员,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3271065/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com