流输出和隐式void *强制转换运算符函数调用 [英] stream output and implicit void* cast operator function invocation

查看:53
本文介绍了流输出和隐式void *强制转换运算符函数调用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

类似

cin>> grade;

其中grade是标准数据类型,返回对cin(istream对象)的引用,该引用启用了级联输入....
但我读到了

where grade is a standard data type returns a reference to cin(istream object) which enables cascaded inputs....
but i read that if

cin >>grade;

在while语句中用作条件语句...流的void *强制转换运算符函数被隐式调用...并且根据对流的成功或失败将对istream对象的引用转换为非null或null指针上一次输入操作...空指针转换为false,非空指针转换为true ...我的问题是:

is used as a condition say in a while statement...the stream's void* cast operator function is called implicitly...and it converts reference to istream object into a non-null or null pointer depending upon success or failure of last input operation...and null pointer converts to false and non-null to true...my questions are:

  1. 什么是void *强制转换运算符函数,它在这里如何工作
  2. 非null指针如何转换为true,null转换为false

推荐答案

1.什么是void *强制转换运算符函数,它在这里如何工作

1.what is the void * cast operator function and how does it work here

它看起来像这样:

operator void* () const {
    return fail() ? 0 : this;
}

问题是:为什么这里不使用 operator bool ?答案是:因为这样可以进行无效的转换,从而可能会隐藏错误.上面是 安全布尔成语 的示例.

The question is: why isn’t an operator bool used here? The answer is: because that allows invalid conversions which may hide bugs. The above is an example of the safe bool idiom.

但是,此实现实际上已过时.这个习语有更好的实现方式.文章对它们进行了解释.

However, this implementation is actually obsolete. There exist better implementations of this idiom; the article explains them.

2.如何将非null指针转换为true,将null转换为false

2.how is non-null pointer converted to true and null to false

这就是C ++的工作方式:任何非null指针在条件中都被认为等同于 true .现在,为什么C ++首先要在这里调用 operator void * ?

This is just how C++ works: any non-null pointer is considered equivalent to true in a conditional. Now, why does C++ invoke the operator void* here in the first place?

本质上,当C ++看到意外类型的对象时,它将尝试应用 one 隐式转换,这将使该对象类型在此上下文中有效.因此,编译器会尝试所有可用的隐式转换,并查看结果类型在这种情况下是否可以接受.

Essentially, when C++ sees an object of an unexpected type, it tries to apply one implicit conversion that would make the object type valid in this context. The compiler therefore tries out all available implicit conversions and looks whether the resulting type would be acceptable in this context.

她正在发生这种情况:编译器看到 while(cin>>等级).它知道 basic_istream while 有条件的情况下无效.因此,它发现在此上下文中存在 operator void * ,而 void * 有效,因此C ++会应用此转换.

This is happening her: the compiler sees while (cin >> grade). It knows that basic_istream isn’t valid in the context of a while conditional. So it finds that there is an operator void*, and a void* is valid in this context so C++ applies this conversion.

这篇关于流输出和隐式void *强制转换运算符函数调用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆