下面的代码将
调用名为 item1 的 Sales_item 对象的成员函数。 -C++ Primer 第 4 版。(书)
// first check that item1 and item2 represent the same book
if (item1.same_isbn(item2))
如果item1的ISBN等于item2
,它将返回true,但是你给出了一些练习,这让我想使用与原始条件相反的效果,而不是等于(显然),所以我这样说,
if (!item1.same_isbn(item2))
编译器将编译,但结果与预期不符,所以有一些东西告诉我代码在哪里有效,但处理了我不期望的东西。
那么,按照标题所说, not("!") 运算符实际上在任何地方都一样工作吗?
the code below will
calls a member function of the Sales_item object named item1. -C++ Primer 4th edi.(book)
// first check that item1 and item2 represent the same book
if (item1.same_isbn(item2))
which will return true if ISBN of item1 is equal to item2
, but thee give some exercise which make me want to use opposite effect to the original condition, not equal(obviously), so I put it like this
if (!item1.same_isbn(item2))
the compiler will compile but the result miss from the expected one, so there something that told me that where code is valid, but processing something that I'm not expected.
so, per title said, does the not("!") operator actually work the same everywhere?
发布评论
评论(3)
!
一元运算符可以应用于任何标量(数字或指针)表达式。操作数转换为bool
,如果表达式为 false,则结果为 true,如果为 true,则结果为 false。对于数字操作数,
!x
相当于x != 0
。对于指针操作数来说也是如此(如果指针是空指针,则为 true。)它也可以应用于任何类型的表达式,只要转换为 bool ,或者,当然,对于定义了重载运算符 ! 的任何类型。
The
!
unary operator can be applied to any scalar (numeric or pointer) expression. The operand is converted tobool
, and the result is true if the expression is false, and false if it's true.For a numeric operand,
!x
is equivalent tox != 0
. It's the same for a pointer operand (it's true if the pointer is a null pointer.)It can also be applied to an expression of any type for which there's a conversion to
bool
, or, of course, for any type for which an overloadedoperator !
is defined.在此示例中:
如果
item1.same_isbn(item2)
等于 false,则上述语句的计算结果为 true。in this example:
The above statement will evaluate to true if
item1.same_isbn(item2)
is equal to false.尝试
注意:确保
item1.same_isbn(item2)
返回true
或false
Try
Note : make sure
item1.same_isbn(item2)
returns atrue
orfalse