1

我正在尝试使用类继承创建一个使用 Caesar Cipher的程序,但友元运算符不允许我使用 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);
}
4

1 回答 1

0

问题getLine是您正在修改Sentence作为const. 只需带走const; 毕竟你想修改它。

于 2013-10-11T21:43:44.903 回答