这个重载错误原因是什么?

C++语言 码拜 9年前 (2015-11-15) 707次浏览
class Person
{       
public:
    Person(){};
    ~Person(){};
    friend ostream& operator<<(ostream& os, const Person& p)
    {   
        os << "本人是" << p.name << ", 今年" << p.age << "身高"
            << p.tall << ",体重" << p.weight << ".\n";
        return os; 
    }   
    friend istream& operator>>(istream& is, const Person& p)
    {   
        is >> p.name;
        return is; 
    }   
private:
    string name;
    int age;
    int tall;
    int weight;
};

出错信息:
cannot convert ‘p.Person::name’ (type ‘const string {aka const std::basic_string<char>}’) to type ‘signed char*’
         is >> p.name;

解决方案:4分
>>运算符的第二个参数,不能为const
解决方案:4分
重载的插入运算符的第二个参数不能为const
const表示在这个函数内不可以修改p的内容
解决方案:4分
包含头文件:#include <string>
friend istream& operator>>(istream& is, const Person& p) 这句不要const,否则无法修改
解决方案:4分
重载>>要注意第二个参数不能为const对象,原因是>>是写入,会修改对象。
所以吧,一定得清楚什么时候需要const,什么时候不需要const,不是随便用的。
解决方案:4分
friend istream& operator>>(istream& is, Person& p) //去掉const
    {   
        is >> p.name;
        return is; 
    }   

CodeBye 版权所有丨如未注明 , 均为原创丨本网站采用BY-NC-SA协议进行授权 , 转载请注明这个重载错误原因是什么?
喜欢 (0)
[1034331897@qq.com]
分享 (0)