C++ 错误:与';不匹配;运营商-';在';温度-5';

C++ 错误:与';不匹配;运营商-';在';温度-5';,c++,C++,错误显示:与“temp-5”中的“operator-”不匹配 我想做的是一个ceasar密码,我知道我还没有完成密码,但我认为即使我完成了它,错误仍然会出现,我应该在类中创建一个重载运算符吗?如果是,怎么做?我认为重载只在两个类之间。temp是类型string,您指定的是减法。将类型更改为支持减法的类型(如int)并相应地更改逻辑,或者为字符串和int实现运算符-,您的变量temp是字符串,而字符串没有减法。像“hello”-“world”这样的语句是没有意义的,因此定义一个语句通常不是一个好主

错误显示:与“temp-5”中的“operator-”不匹配
我想做的是一个ceasar密码,我知道我还没有完成密码,但我认为即使我完成了它,错误仍然会出现,我应该在类中创建一个重载运算符吗?如果是,怎么做?我认为重载只在两个类之间。

temp
是类型
string
,您指定的是减法。将类型更改为支持减法的类型(如
int
)并相应地更改逻辑,或者为
字符串
int
实现
运算符-
,您的变量
temp
是字符串,而字符串没有减法。像
“hello”-“world”
这样的语句是没有意义的,因此定义一个语句通常不是一个好主意

在您的例子中,您甚至尝试从字符串中减去一个数字(“hello”-5),这也没有意义

如果要计算某个值,请使用数字类型(例如
int
float
double
long


看看你们的代码,我很确定你们想用字符串中单个字符的数值来计算一些东西来“加密”它们。为此,必须逐个字符地对字符串的字符进行操作。字符类型是一种数字类型,因此计算
'T'-'a'
很正常,而
“T”-“a”
没有意义。

不要为字符串实现
运算符-
。@LightnessRacesinOrbit:我已经澄清了我答案的这一部分。想解释一下你的评论吗?这样一个操作符会非常令人惊讶,而且它的语义也不清楚。避免创造一个的诱惑;这将是经营者滥用权力的完美例子。看看乌尔泽特的答案。
#include <iomanip>
#include <string>
#include <cstdlib>
#include <iostream>

using namespace std;

class STLstring
{
    private:
        string word;
    public:
    STLstring()
    {
        word = "";
    }
    void setWord(string w);
    string getWord();

};

class EncryptString:public STLstring
{
    private:
        void encrypt();
        void decrypt();
};


/*****************IMPLEMENTATION*******************/

void STLstring::setWord(string w)
{
    void encrypt();
    word = w;
    cout << word;
}

string STLstring::getWord()
{
    void decrypt();
    return word;
}

void EncryptString::encrypt()
{
    string temp = getWord();

    temp = (temp - 5) %26;



    setWord(temp);
}

void EncryptString::decrypt()
{
    string temp = getWord();



    setWord(temp);
}

int main()
{
    string word = "";
    EncryptString EncrptStr;

    cout << "Enter a word and I will encrypt it so that you cannot read it any longer." << endl;
    getline(cin, word);

    cout << "\nHere is the encrypted word..." << endl;
    EncrptStr.setWord(word);

    cout << "\nHere is the decrypted word..." << endl;
    cout << EncrptStr.getWord() << endl;
}
temp = (temp - 5) %26;