简体   繁体   English

C ++错误; 我应该如何解释其含义?

[英]c++ error; how should i interpret its meaning?

This may be a silly thing to ask but I am confused with compilation error while trying to use the safe bool idiom while reading this article. 这可能是一个愚蠢的事情要问,但我很困惑与编译错误,而试图在阅读使用安全布尔成语文章。 Below is my code and I have indicated the lines where i get errors in main() function. 以下是我的代码,并指出了在main()函数中出现错误的行。

// is OK case
class BoolVer_OK {
    bool m_OK;

public:
    BoolVer_OK(bool ok) : m_OK(ok){}
    operator bool() {  return m_OK; }
};

//  Not OK Case
class BoolVer_NotOK {
    bool m_notOK;

public:
    BoolVer_NotOK(bool ok) : m_notOK(!ok){}
    bool operator !() const{ reportexecution;  return !m_notOK; }
};

main()
{
    BoolVer_OK ok(true);
    BoolVer_NotOK notOK(true);
    ok<<1;  // Line#1     is valid
    notOK << 1; // Line#2: error: inavlid operand to binary expression ('BoolVer_notOK' and 'int')
return 0;
}

Why we didn't get error at #Line1 while we get at #Line2. 为什么我们在#Line2上却没有在#Line1上出错。 Both results in a boolean value before << operator. 两者均导致<<运算符之前的布尔值。

ok supports operator bool , and C++ has this nice functionality called implicit casting and also promotion, and in this case for the binary shift operator << , the bool is promoted to an int , and this is then shifted by 1. ok支持operator bool ,并且C ++具有此出色的功能,称为隐式转换和提升。在这种情况下,对于二进制移位运算符<<bool值被提升为int ,然后将其移位1。

In the second case, you've not provided that operator, and hence there is nothing to implicitly convert (and promote) to int, and you get the error. 在第二种情况下,您没有提供该运算符,因此没有任何隐式转换(和提升)为int的操作,并且您会得到错误。 Try calling !notOk before the shift, now there is a bool, which will be promoted. 尝试在!notOk前致电!notOk ,现在有一个布尔值,它将被提升。

I don't think the compiler would automatically insert a call to operator! 我认为编译器不会自动插入对operator!的调用operator! and then negate that to get you the bool you want. 然后取而代之,以获取所需的bool From what I see in the link you provided, they do their tests with a double negation, !! 根据我在您提供的链接中看到的内容,他们在两次否定的情况下进行测试!! .

ok<<1;  // Line#1     is valid
notOK << 1; // Line#2: error: inavlid operand to binary expression ('BoolVer_notOK' and 'int')

This happens because ok is converted to bool implicitly (overloaded operator), whereas notOK doesn't have that operator. 发生这种情况是因为ok被隐式转换为bool (重载运算符),而notOK没有该运算符。

Test out the following code: 测试以下代码:

  BoolVer_OK ok(true);
  BoolVer_NotOK notOK(true);
  int z = ok<<1;  // is valid
  //notOK << 1; // error: inavlid operand to binary expression ('BoolVer_notOK' and 'int')
  int x = false << 1;
  return 0;

The booleans on the left-side of the shift operator are converted to ints and then shifted. 移位运算符左侧的布尔值将转换为int,然后进行移位。

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

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