mercredi 18 août 2021

C++ Primer 5th Edition (Stanley) - Question on exercise 7-39

Working through some exercises in C++ Primer 5th Ed (Stanley) and on exercise 7-39.

  1. Class for exercise 7-39.

    class Sales_data {
    public:
    
    // defines the default constructor as well as one that takes a string argument
    Sales_data(std::string s = ""): bookNo(s) {}
    
    // remaining constructors unchanged
    Sales_data(std::string s, unsigned cnt, double rev): bookNo(s), units_sold(cnt), revenue(rev*cnt) {}
    
    Sales_data(std::istream &is) { read(is, *this); }
    
    // remaining members as before
    
  2. Question:
    Exercise 7.39: Would it be legal for both the constructor that takes a string and the one that takes an istream& to have default arguments? If not, why not?

  3. My answer:
    Yes. I can have the following:

     Sales_data(std::string s = ""): bookNo(s) {}
     Sales_data(std::istream &is = std::cin) { read(is, *this); }
    

The above are valid.
However there are some site with solution for this C++ Primer 5th edition which says no as below:

https://github.com/Mooophy/Cpp-Primer/tree/master/ch07 (you need to scroll down to exercise 7-39. Answer does not make sense)

https://github.com/jaege/Cpp-Primer-5th-Exercises/blob/master/ch7/7.39.md (this answer does not make sense at all)

I would like some other opinion if i am missing something. I still stand by my answer to far.

Thx

Aucun commentaire:

Enregistrer un commentaire