我尝试在 Student 类中重载 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 时,我收到错误消息“Segmentation Fault”。
我将 char* snum;
更改为 char snum;
,它返回编译器错误 The operation "std::istream>> const char"is illegal.
感谢您的帮助。
最佳答案
你需要 snum 指向分配内存,然后你可以用数据输入它,例如:
char* p_var = new char[20]; // 20 bytes allocation
// ... using p_var
delete[] p_var; // Releasep_var memory
在您的情况下,您应该在 Ctor 中进行分配,在 Dtor 中进行释放。 您可以阅读此内容以获取更多信息: http://www.cplusplus.com/doc/tutorial/basic_io/
关于c++ - C++中的重载ostream运算符错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30497243/