相关疑难解决方法(0)

我什么时候可以使用显式运算符bool而无需强制转换?

我的班级明确转换为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)

我还可以tbool没有演员阵容的情况下使用?

c++ implicit-conversion

29
推荐指数
1
解决办法
6303
查看次数

在if语句中,cin如何评估为true?

我以为:

if (true) 
{execute this statement}
Run Code Online (Sandbox Code Playgroud)

那么if (std::cin >> X)当没有什么"真实"的时候,如何执行为真呢?我能理解,如果它是if ( x <= y)if ( y [operator] x ),但什么样的逻辑是"的IStream =真的吗?".

c++ if-statement

7
推荐指数
3
解决办法
787
查看次数

在c ++中禁用隐式转换

是否可以在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)

c++

2
推荐指数
1
解决办法
994
查看次数

标签 统计

c++ ×3

if-statement ×1

implicit-conversion ×1