【问题标题】:How can I store a string of characters using friend operators?如何使用友元运算符存储字符串?
【发布时间】:2013-10-11 21:14:58
【问题描述】:

我正在尝试使用类继承创建一个使用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);
}

【问题讨论】:

    标签: c++ friend getline


    【解决方案1】:

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-09-17
      • 2014-02-19
      • 1970-01-01
      • 2015-10-28
      • 2012-08-11
      • 1970-01-01
      • 1970-01-01
      • 2017-07-26
      相关资源
      最近更新 更多