gpt4 book ai didi

c++ - 如何为参数中的隐式类型转换定义构造函数?

转载 作者:行者123 更新时间:2023-12-02 10:22:26 26 4
gpt4 key购买 nike

最近我在<filesystem>中使用函数,例如std::filesystem::exists。这些函数接受std::filesystem::path。我注意到将像const char*这样的"/abc"传递给像std::filesystem::exists那样的功能,例如std::filesystem::exists("/abc")
我的问题是,似乎在将const char*传递给std::filesystem::exists时,我们正在进行一些从const char*filesystem::path的隐式转换。

  • 哪个构造函数在filesystem::path类上处理此问题?
  • 如何为这种类型的转换编写构造函数?下面的代码似乎不起作用,并且我不确定出什么问题。 (我对C++有点陌生)。
  • class A {
    A(const char*& msg) {
    std::cout << msg << std::endl;
    }
    };

    void func(const A& p) {
    }

    int main(int argc, const char * argv[]) {
    func("123"); // No matching function for call to 'func'
    return 0;
    }

    最佳答案

    首先,将构造函数设为Public。

    其次,您代码中A的构造函数采用的是const char*&,它是对const char*的引用,因此const char*不会隐式转换为A,因为const char*&是左值引用,而const char*是右值(基本上是无名临时性)

    试试这个会起作用

    #include<iostream>
    class A {
    public:
    A(const char* msg) {
    std::cout << msg << std::endl;
    }
    };

    void func(const A& p) {
    }

    int main(int argc, const char * argv[]) {
    func("123"); // No matching function for call to 'func'
    return 0;
    }

    Which constructor handles this on filesystem::path class



    根据 cppreference,(5)构造函数
    template< class Source >
    path( const Source& source, format fmt = auto_format );

    负责从 const char*std::filesystem::path的隐式类型转换

    关于c++ - 如何为参数中的隐式类型转换定义构造函数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59527997/

    26 4 0
    Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
    广告合作:1813099741@qq.com 6ren.com