c++ - C++中的重载ostream运算符错误

标签 c++ operator-overloading

我尝试在 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/

相关文章:

c++ - C++ 中的重载运算符和取消引用

c++ - 类模板上的运算符重载

c++ - 我们可以同时从 C++ 字符串中删除两个子字符串吗?

c++ - 如何将文本(诗歌)分成几行(字符串/字符[])并找到每一行的最后一个词

c++ - 排序这个词的排序标准?

c++ - 具有运算符重载的 accumulate()

c++ - 运算符重载 C++/我的代码放在哪里?

C++ Windows IOCP - HTTP POST 数据丢失

c++ - 需要接受用户的响应才能执行程序

c++ - 目标文件中的 ostream 运算符会发生什么?