如何使用友元操作符存储一串字符?

时间:2013-10-11 21:14:59

标签: c++ friend getline

我正在尝试使用类继承创建一个使用Caesar Cipher的程序,但是friend运算符不允许我使用getline。我已经尝试查找不同的重载getline的方法,但我不确定我做错了什么(我最近才停止使用命名空间std,因此可能存在一些错误)。

它仍在进行中。我不知道我是否需要长度,或者如果那些重载+运算符实际上会为旧字符串添加额外的单词,例如(虽然我可以稍后解释,我只想知道如何在这里正确使用getline )。任何帮助表示赞赏。

#include <iostream>
#include <string>


class Sentence{

    private:
        std::string codeSentence;
        int length;

    public:
        Sentence();
        Sentence(std::string codeSentence);
        Sentence(const Sentence &obj);
        ~Sentence();
        void setS (std::string codeSentence);
        std::string getS() const;
        Sentence & operator = (const Sentence &obj);
        Sentence operator +(const Sentence &obj) const;
        Sentence operator +(std::string codeSentence) const;
        friend Sentence operator +(std::string codeSentence, const Sentence &obj);
        friend std::ostream & operator << (std::ostream & out, const Sentence &obj);
        friend std::istream & operator >> (std::istream & in, Sentence &obj);
        friend std::istream & getline (std::istream & in, const Sentence & obj);
    };

Sentence::Sentence(){
}

Sentence::Sentence(const Sentence &obj){
    (*this) = obj;
}

Sentence::Sentence(std::string codeSentence){
    this->codeSentence = codeSentence;
}

Sentence::~Sentence(){
}

void Sentence::setS(std::string codeSentence){
    this->codeSentence = codeSentence;
}

std::string Sentence::getS() const{
    return (this-> codeSentence);
}

Sentence & Sentence::operator=(const Sentence &obj){
    this->codeSentence = obj.codeSentence;
    return (*this);
}

Sentence Sentence::operator+(const Sentence &obj) const{
    return (Sentence(this->codeSentence + ' ' + obj.codeSentence));
}

Sentence Sentence::operator+(std::string codeSentence) const{
    return (Sentence(this->codeSentence + ' ' + codeSentence));
}

Sentence operator+(std::string codeSentence, const Sentence &obj){
    return (Sentence(codeSentence + ' ' + obj.codeSentence));
}

std::istream & getline (std::istream & in, const Sentence & obj){
    if (in >> obj.length)
        getline(in, obj.codeSentence);
    return (in);
}

std::istream & operator >> (std::istream & in, Sentence &obj){

    in.getline(obj.codeSentence, sizeof(obj.codeSentence));
    return (in);
}

1 个答案:

答案 0 :(得分:0)

getLine的问题在于您正在修改以Sentence传入的const。只需带走const;毕竟你想修改它。