相关疑难解决方法(0)

为什么在C++中有从指针到bool的隐式类型转换?

考虑foo具有两个这样定义的构造函数的类:

class foo
{
public:
    foo(const std::string& filename) {std::cout << "ctor 1" << std::endl;}
    foo(const bool some_flag = false) {std::cout << "ctor 2" << std::endl;}
};
Run Code Online (Sandbox Code Playgroud)

使用字符串文字实例化类,并猜测调用哪个构造函数?

foo a ("/path/to/file");
Run Code Online (Sandbox Code Playgroud)

输出:

ctor 2

我不了解你,但我没有发现编程历史中最直观的行为.我打赌它有一些聪明的理由,但我想知道它可能是什么?

c++ types boolean implicit

14
推荐指数
2
解决办法
5323
查看次数

为什么我的变量将std :: string转换为bool?

std::variant可以是空的(std::monostate),包含一个int,一个std::string或一个bool.

当我想用字符串提供它时,给定为var = "this is my string",它将转换为a bool而不是字符串.如果我明确声明类型,它可以工作var = std::string("this is my string").为什么会这样,我能做些什么来避免它?

#include <string>
#include <variant>
#include <iostream>

int main()
{
    using var = std::variant<std::monostate, int, std::string, bool>;

    var contains_nothing;    
    var contains_int = 5;
    var contains_string = "hello";
    var contains_expl_string = std::string("explicit hello");
    var contains_bool = false;

    auto visitor = [](auto&& arg){
            using T = std::decay_t<decltype(arg)>;
            if constexpr (std::is_same<T, std::monostate>())
                std::cout<<"nothing\n";
            else if constexpr …
Run Code Online (Sandbox Code Playgroud)

c++ variant c++17

13
推荐指数
1
解决办法
2089
查看次数

为什么 const 指针会意外转换为 bool?

我有一个带有两个构造函数的类。一为bool一为A*

struct B
{
    explicit B(bool b)
    {
      std::cout << "B(bool)" << std::endl;
    }
    explicit B(A*)
    {
      std::cout << "B(A*)" << std::endl;
    }
};
Run Code Online (Sandbox Code Playgroud)

当 B 应该用const A*而不是A*-构造时,const A*将转换为bool.

const A a;
B b(&a);
Run Code Online (Sandbox Code Playgroud)

输出: B(bool)


所需的解决方案是

编译器错误:“B(const A*) 没有有效的构造函数”

我已经尝试过使用explicit关键字,但是没有用。

在coliru运行示例

c++ casting compiler-errors boolean-expression

3
推荐指数
1
解决办法
134
查看次数