V2EX = way to explore
V2EX 是一个关于分享和探索的地方
Sign Up Now
For Existing Member  Sign In
jdz
V2EX  ›  C++

cpp 一个隐式转换奇怪的现象

  •  
  •   jdz · Feb 11, 2025 · 2696 views
    This topic created in 442 days ago, the information mentioned may be changed or developed.

    std::map<std::string, std::string> a; std::string m = 2; //编译失败 a["hello"] = 1; //编译成功 为什么呢

    4 replies    2025-02-11 15:48:27 +08:00
    Orchestraa
        1
    Orchestraa  
       Feb 11, 2025
    m 是构造,a 是赋值
    Shatyuka
        2
    Shatyuka  
       Feb 11, 2025
    构造函数不要 char ,赋值可以。
    试试:
    ```cpp
    std::string n;
    n = 3;
    ```
    yanqiyu
        3
    yanqiyu  
       Feb 11, 2025
    构造函数没有接一个 char 的构造[1],但是有接一个 char 的 assign[2]
    [1]: https://en.cppreference.com/w/cpp/string/basic_string/basic_string
    [2]: https://en.cppreference.com/w/cpp/string/basic_string/operator%3D
    Opportunity
        4
    Opportunity  
       Feb 11, 2025
    前一个是拷贝构造,后一个是赋值。

    ```
    std::string m;
    m = 2;
    ```

    也可以的。https://en.cppreference.com/w/cpp/string/basic_string/operator%3D 看示例 6
    About   ·   Help   ·   Advertise   ·   Blog   ·   API   ·   FAQ   ·   Solana   ·   3161 Online   Highest 6679   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 33ms · UTC 14:12 · PVG 22:12 · LAX 07:12 · JFK 10:12
    ♥ Do have faith in what you're doing.