gpt4 book ai didi

c++重载的友元函数无法访问私有(private)成员

转载 作者:行者123 更新时间:2023-11-28 04:48:49 25 4
gpt4 key购买 nike

目前正在做一个项目,我的教授要求我们重载流提取和输入运算符。我复制了他给我们的标题以开始我的实现。这是我的标题 student.h:

// @file student.h
#ifndef STUDENT_H
#define STUDENT_H
#include <string>
using namespace std;
class Student {
/** add all the setter and getter methods **/
/**
* @param is the input stream
* @param course the student object reference
* @return the input stream
*/
friend istream &operator >> (istream &is, Student &student);
/**
* @param os the output stream
* @param course the student object reference
* @return the output stream
*/
friend ostream& Student::operator << (ostream& os, const Student& student);

public:
Student();
Student(string firstName, string lastName, int id, char grade);

void setFirstName(string firstName);
string getFirstName();


private:
string firstName;
string lastName;
int id;
char grade;
};
#endif /* STUDENT_H */

这是我在文件 student.cpp 中使用的定义

#include "student.h"
#include <iostream>
using namespace std;


istream &operator >> (istream &is, Student &student) {
is >> student.firstName;
}

CLion 一直告诉我 firstName 是私有(private)的,因此无法访问,有什么明显的我遗漏的吗?我检查并仔细检查了我的格式,并将符号移动了很多,但我很难说出它是什么。

是的,我已经查看了他在使用的命名空间方面遇到问题的同名问题,尝试过但没有看到任何结果。非常感谢任何帮助。

最佳答案

我无法解释错误消息,但该函数必须返回一个值。

istream &operator >> (istream &is, Student &student) {
return (is >> student.firstName);
}

修复它和缺少的构造函数等,以及 main(),它应该可以正常编译。

附言将 Student 类放在一个完全属于您的命名空间中,永远不要在头文件中编写using namespace std;

关于c++重载的友元函数无法访问私有(private)成员,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48634078/

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