c ++中重载的ostream操作符错误

时间:2015-05-28 04:25:07

标签: 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. 谢谢你的帮助。

2 个答案:

答案 0 :(得分:2)

你需要 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/

答案 1 :(得分:1)

通过使用以下更改告诉我您的问题是否得到解决......

class Student
{
     private:
        char snum;
        char name;
        char email;
    public:
        Student(){};
        ~Student(){};
        friend std::ostream& operator<< (std::ostream&,Student&);
        friend std::istream& operator>> (std::istream&,Student&);

};


std::ostream& operator<< (std::ostream& output,Student& c)
{
    output<<c.snum<<", "<<c.name<<", "<<c.email<<endl;
    return output;
}
std::istream& operator>> (std::istream& input, Student& cN)
{
    cout<<"Input number: ";
    input>>cN.snum;
    input>>cN.name;
    input>>cN.email;
    return input;
}


int main() 
{
    Student st;
   std::cin >> st;
    std::cout << st << std::endl;
    return 0;
}

使用字符串或字符数组或在使用cin之前为char * x指定一些内存...