简体   繁体   English

C ++在类的成员函数中使用cin

[英]C++ Using cin in member functions of a class

I am trying to use cin to read private members of a class within a member function of the class and i am getting an error [Error] no match for 'operator>>' in 'std::cin >> ((const Course*)this)->Course::courseID' ? 我正在尝试使用cin来读取类的成员函数中的类的私有成员,并且在'std :: cin >>((const Course * )this)-> Course :: courseID'吗? Is it possible to do that? 有可能这样做吗? Here is my code 这是我的代码

//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

Using std::cin is considered writing to member data. 考虑使用std::cin写入成员数据。 But you can not change the data members using a const qualified member function. 但是您不能使用const限定成员函数来更改数据成员。 Remove the const specifier from the function declaration and definition if you want to achieve that functionality: 如果要实现该功能,请从函数声明和定义中删除const说明符:

void Course::EnterCourse();

More info on the subject in these SO posts: 这些SO帖子中提供了有关该主题的更多信息:
Meaning of “const” last in a C++ method declaration? C ++方法声明中“ const”最后的含义?
What is meant with “const” at end of function declaration? 函数声明末尾的“ const”是什么意思?

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM