gpt4 book ai didi

c++ - 如何使用友元运算符存储一串字符?

转载 作者:太空宇宙 更新时间:2023-11-04 14:00:57 25 4
gpt4 key购买 nike

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

最佳答案

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

关于c++ - 如何使用友元运算符存储一串字符?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19327378/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com