我正在尝试使用cin来读取类的成员函数中的类的私有成员,并且我收到错误[错误]不匹配'operator>>'在'std :: cin>> ((const课程*)这个) - > Course :: courseID'? 有可能吗?这是我的代码
//Course.h
#ifndef Course_H
#define Course_H
#include<string>
#include<iostream>
using namespace std;
class Course
{
private:
string courseID;
string courseName;
int credits;
Course * nextCourse;
public:
void EnterCourse() const;
void SetNext(Course *);
string GetCourseID() const;
string GetCourseName() const;
int GetCredits() const;
};
void Course::EnterCourse() const
{
cout<<"=======Enter Course Information========\n"
<<"Enter Course ID: \n";
cin>>courseID;
cout<<"Enter Course Name: \n";
cin>>courseName;
cout<<"Enter credits: \n";
cin>>credits;
}
string Course::GetCourseID() const
{
return courseID;
}
string Course::GetCourseName() const
{
return courseName;
}
int Course::GetCredits() const
{
return credits;
}
void Course::SetNext(Course * cou)
{
nextCourse=cou;
}
#endif
答案 0 :(得分:2)
使用std::cin
被视为写入成员数据。但是,您无法使用const
限定成员函数更改数据成员。如果要实现该功能,请从函数声明和定义中删除const
说明符:
void Course::EnterCourse();
这些SO帖子中关于这个主题的更多信息:
Meaning of “const” last in a C++ method declaration?
What is meant with “const” at end of function declaration?