【问题标题】:what is ambiguous conversion for functional-style cast in c++ Initialization什么是 c++ 初始化中函数式转换的模棱两可的转换
【发布时间】:2021-08-25 06:01:28
【问题描述】:

我很困惑,刚学C++

class Person {
public:
    string name;
    double weight;
   
    Person(string  _name):name(_name) {}
  
    Person(string n = "", double a = 0.0) {
        name = n;
        weight = a;
    }

};

int main(){

    // It`s ok.
    Person p = Person("zhangwen",12);
    cout << p.name << endl;
    
    // It`s ok.
    Person p3 = Person();
    cout << p3.weight << endl;
    
    
    // When I use it this way, the following error occurs. why????
    // ambiguous conversion for functional-style cast from 'const char [7]' to 'Person'
    Person p2 = Person("hhh");
    cout << p2.name << endl;
    
    
    return 0;
}

【问题讨论】:

  • 编译器不知道它应该使用哪个构造函数,两者都一样好。您可以删除第一个构造函数 (Person(string _name)) 来解决问题(最好重写第二个构造函数以像第一个构造函数一样使用 member initializer list)。

标签: c++


【解决方案1】:

我收到了error: call of overloaded 'Person(const char [4])' is ambiguous

运行:https://wandbox.org/permlink/hQPbL1k8GLetbphR

因为在这种情况下两个构造函数都可以使用

 Person(string  _name):name(_name) {} // Person("hhh") is a valid
 // candidate with const char [] => to string

Person(string n = "", double a = 0.0) // Person("hhh") will be seen as 
//Person("hhh", 0)

我建议

class Person {
public:
    std::string name {};
    double weight{}; // note the '{}' it mean than the default value is `0`. 
    // If you don't do that and use weight you will have an 
    // undefined behavior (a bug)
   
    Person(std::string  _name, double _weight = 0):name(_name) , weight(_weight) {}
    Person() = default;

};

演示:https://wandbox.org/permlink/Ti9ilvYqsSHcww6N

顺便说一句:Why is “using namespace std;” considered bad practice?

【讨论】:

  • 我一直有一个疑问,为什么编译器在编译时没有警告类中未定义的成员?例如重量。
  • 我不知道,你可以看这里:stackoverflow.com/questions/17705880/…。如果回答了最初的问题,请接受答案(欢迎任何投票;))
猜你喜欢
  • 2015-11-19
  • 1970-01-01
  • 2019-08-10
  • 2013-08-08
  • 1970-01-01
  • 1970-01-01
  • 2020-11-21
  • 1970-01-01
  • 2022-01-02
相关资源
最近更新 更多