C++ addition overload ambiguity

前端 未结 5 1370
时光说笑
时光说笑 2020-12-21 13:14

I am coming up against a vexing conundrum in my code base. I can\'t quite tell why my code generates this error, but (for example) std::string does not.

cla         


        
5条回答
  •  渐次进展
    2020-12-21 13:47

    It is sufficient in this case just to define on operator+:

    String operator+(const String& lval, const String& rval);
    

    Because you provide a constructor taking a char*, a String can be constructed from a char* during the call to operator+. For example:

    String hello = "Hello, ";
    const char* world = "world!";
    
    String helloWorld = hello + world;
    

    A temporary String will be constructed with the contents of the char* world (because your constructor is not explicit), then the two String objects will be passed to operator+.

提交回复
热议问题