简体   繁体   English

C ++中具有类/对象的逻辑运算符

[英]Logical operators with class/objects in C++

Completely new to C++. 完全不熟悉C ++。 Trying to understand classes and objects, so far I get the gist of it, as it's nothing too complicated for the very basics. 到目前为止,我试图理解类和对象的要点是,对于基本知识而言,它并没有太复杂。 However, this code I have wrote is not working as intended. 但是,我编写的这段代码无法正常工作。 It works somewhat, however it asks for user input twice. 它有些起作用,但是需要两次用户输入。

#include <iostream>
#include <string>
using namespace std;

class FooFoo {
public :

string GetName() {
    cin >> name;
    return name;
}

private:
    string name;
};

int main()
{
FooFoo object;
if (object.GetName() == "John" || object.GetName() == "Chris")
{
    cout << "Yes";

}
else {
    cout << "No";
}

}

If I input "John", it will return yes right away. 如果我输入“ John”,它将立即返回“是”。 However, when I input anything else, it will prompt me to enter something again, and then the if/else acts accordingly to whatever I inputted. 但是,当我输入其他任何内容时,它将提示我再次输入内容,然后if / else会根据我输入的内容进行相应的操作。

You call object.GetName() twice which causes the input to be asked for twice. 您调用object.GetName()两次,这将导致要求输入两次。 Store the result of this function to a variable and use that in the if statement. 将此函数的结果存储到变量中,并在if语句中使用它。 The || || statement is short-circuited if the first expression is true. 如果第一个表达式为真,则该语句会短路。 This leads to the second call not being executed if the first is true. 如果第一个为true,则这导致第二个调用无法执行。

That is because GetName() is asking for input every time, 这是因为GetName()每次都要求输入,

So the first time it is asking for x, if x isnt john it goes to the next test, which then gets input and tests that against x = chris. 因此,第一次请求x时,如果x不是john,则转到下一个测试,该测试然后获取输入并针对x = chris进行测试。

try changing it to this: 尝试将其更改为此:

int main()
{
FooFoo object;
string test = object.GetName()
if (test == "John" || test == "Chris")
{
    cout << "Yes";

}
else {
    cout << "No";
}

}

Hope that helps 希望能有所帮助

Your current if statement effectively evaluates to: 您当前的if语句有效评估为:

if (object.GetName() == "John")
  cout << "Yes";
else if (object.GetName() == "Chris")
  cout << "Yes";
else
  cout << "No";

Try entering Chris followed by John and you should get No . 尝试先输入Chris ,再输入John然后您应该会得到No

Just call getName() before the if statement, store the value in a local variable, then test that instead: 只需在if语句之前调用getName() ,将值存储在本地变量中,然后进行测试:

string name = object.GetName();
if (name == "John" || name == "Chris")
  cout << "Yes";
else
  cout << "No;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM