我試着重載ostream的操作員一類學生如下:重載ostream的操作錯誤++
//Student.h
class Student
{
public:
Student(){}
~Student(){}
friend std::ostream& operator<< (std::ostream&,const Student&);
friend std::istream& operator>> (std::istream&,const Student&);
private:
char* snum;
};
//Student.cpp
#include "Student.h"
std::ostream& operator<< (std::ostream& output,const Student& c)
{
output<<c.snum<<", "<<c.name<<", "<<c.email<<endl;
return output;
}
std::istream& operator>> (std::istream& input,const Student& cN)
{
cout<<"Input number: ";
input>>cN.snum;
return input;
}
//main.cpp
#include "Student.h"
int main()
{
Student st;
std::cin >> st;
std::cout << st << std::endl;
return 0;
}
但是,當我輸入的SNUM,我得到錯誤信息「段錯誤」。 我將char* snum;
更改爲char snum;
,它返回編譯器錯誤The operation "std::istream>> const char" is illegal.
感謝您的幫助。
'snum'不指向任何東西。使用'std :: string'。 – user657267
@ user657267錯誤信息是'The operation'std :: istream >> const std :: string「is illegal。」 – Roaid
'std :: istream&operator >>(std :: istream&input,Student&CN)' – user657267