1

I'm confused, just learning 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;
}
Yksisarvinen
  • 18,008
  • 2
  • 24
  • 52
littleZ
  • 71
  • 2
  • Compiler doesn't know which constructor it should use, both are just as good. You can remove your first constructor (`Person(string _name)`) to solve the issue (and preferably rewrite the second one to use [member initializer list](https://stackoverflow.com/questions/1711990/what-is-this-weird-colon-member-syntax-in-the-constructor) like the first one does). – Yksisarvinen Jun 08 '21 at 08:07

1 Answers1

0

I got error: call of overloaded 'Person(const char [4])' is ambiguous

run : https://wandbox.org/permlink/hQPbL1k8GLetbphR

Because both constructor can be use in this case

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

and

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

I sugest

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;

};

Demo : https://wandbox.org/permlink/Ti9ilvYqsSHcww6N

Btw : Why is “using namespace std;” considered bad practice?

Martin Morterol
  • 2,560
  • 1
  • 10
  • 15
  • I always have a question, why the compiler does not warn about the undefined members in the class when compiling? For example weight. – littleZ Jun 08 '21 at 08:27
  • I don't know, you can look here : https://stackoverflow.com/questions/17705880/gcc-failing-to-warn-of-uninitialized-variable . If the inital question is answered, please accept the answer (and any up-vote is welcome ;) ) – Martin Morterol Jun 08 '21 at 08:39