【问题标题】:no operator matches || these operands没有运算符匹配 ||这些操作数
【发布时间】:2016-11-07 20:47:02
【问题描述】:

您好,我在使用 C++ 中的 if 语句时遇到了问题。当我编译我的代码时,我收到一条错误消息,指出“没有运算符“||”匹配这些操作数”。有什么猜测吗?该项目是我在 Visual Studio 中创建的基于文本的小型游戏。

#include "stdafx.h"
#include <iostream>
#include <iomanip>
#include <string>
#include <cmath>
#include <fstream>

using namespace std;

//Prototypes
void introScreen(int);
string characterCreation(string);



int choice;
string characterName, wepon1, wepon2, bow, sword, mace;

const string sword = sword;
const string bow = bow;
const string mace = mace;

// Functions 

int main()
{
    introScreen(choice);

    return 0;
}


void introScreen(int choice)
{

    cout << "----------------------------------------\n"
        << "Welcome to the arena!\n"
        << "Select a menu option\n"
        << "-----------------------------------------\n"
        << "1. New Game\n"
        << "2. Load\n"
        << "3. Exit\n\n"
        << "Enter your desired number ";
    cin >> choice;

    if (choice == 1)
        characterCreation(characterName);
    else
        if (choice == 2)
            exit(0);
        else
            if (choice == 3)
                exit(1);

}


string characterCreation(string characterName,string wepon1,string wepon2, const string bow, const string sword, const string mace)
{

    cout << "Welcome to the character creation menu!\n"
        << "Enter your name\n"
        << "Name: ";
    cin.ignore();
    getline(cin, characterName);

    ofstream loadFile("Save.txt");
    loadFile << characterName << endl;

    cout << "\nEnter 2 wepons\n"
        << "Wepon list\n\n"
        << "Sword\n"
        << "Mace\n"
        << "Bow\n";
    cin >> wepon1, wepon2;

    if (wepon1 || wepon2 != bow || sword || mace)
    {
        cout << "\n\nThose wepons are invalid! Enter new ones\n";
        cout << "\nEnter 2 wepons\n"
            << "Wepon list\n\n"
            << "sword\n"
            << "mace\n"
            << "bow\n";
        cin >> wepon1, wepon2;
    }

    loadFile << wepon1 << endl
        << wepon2 << endl;


    return characerName;
}

【问题讨论】:

  • 逻辑“或”不能这样工作。您需要将 each 武器与 each 类型进行比较。
  • 哦,这也行不通:cin &gt;&gt; wepon1, wepon2;
  • @Mark Ransom 在 gcc 上使用-Wall,如果在看似毫无意义的场景中使用逗号运算符,则会发出警告。
  • 为什么人们一直假设逻辑运算符会扩展为周围运算的笛卡尔积?
  • 这有点奇怪:const string sword = sword;Recommend a bit of book-reading

标签: c++


【解决方案1】:

'||'运算符是对逻辑条件的评估,您要求它评估字符串类型。通常,当评估字符串值时,它们被评估为 如果 (weapon1 != "") 那么...

另外,请注意设置值的方式。字符串值在双引号内传递。

【讨论】:

  • 非常感谢!我没有意识到这一点。感谢您的帮助
猜你喜欢
  • 2013-01-25
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-08-07
  • 2018-05-02
相关资源
最近更新 更多