我的班级明确转换为bool:
struct T {
explicit operator bool() const { return true; }
};
Run Code Online (Sandbox Code Playgroud)
我有一个例子:
T t;
Run Code Online (Sandbox Code Playgroud)
要将它分配给类型的变量bool,我需要编写一个强制转换:
bool b = static_cast<bool>(t);
bool b = bool(t);
bool b(t); // converting initialiser
bool b{static_cast<bool>(t)};
Run Code Online (Sandbox Code Playgroud)
我知道我可以在没有强制转换的条件下直接使用我的类型,尽管有explicit限定符:
if (t)
/* statement */;
Run Code Online (Sandbox Code Playgroud)
我还可以t在bool没有演员阵容的情况下使用?
我以为:
if (true)
{execute this statement}
Run Code Online (Sandbox Code Playgroud)
那么if (std::cin >> X)当没有什么"真实"的时候,如何执行为真呢?我能理解,如果它是if ( x <= y)或if ( y [operator] x ),但什么样的逻辑是"的IStream =真的吗?".
是否可以在C/C++中禁用隐式转换.
假设我想写一个有效函数,只让我输入 integers in range [1,10]
我已经写了:
#include <iostream>
using namespace std;
int main( )
{
int var=0;
cout << "Enter a number (Integer between 1 to 10) : ";
while( (!(cin >> var )) || (var > 10 ) || (var < 1) )
{
cout << "U nuts .. It can only be [1,10]\n";
cin.clear();
cin.ignore(std::numeric_limits<std::streamsize>::max(),'\n');
cout << "Enter a number (Integer between 1 to 10) : ";
}
cout << "\nYou entered : " << var;
return …Run Code Online (Sandbox Code Playgroud)