简体   繁体   中英

Why do I get compilation error in this code?

I have this code and when I compile it I get compilation error.

    #include <iostream>
    #include <string>
    using namespace std;

    struct Date{
      int day;
      int month;
      int year;
    };

  class appointment{
     public:
       appointment(int d,int m,int y,string n);
     private:
       struct Date date;
       string name;

   };

   int main()
   {
     appointment a(22,12,2019,"James"); 
   } 

   appointment::appointment(int d,int m,int y,string n) :
      date.day(d),date.month(m),date.year(y),name(n)
   {

   }

However, when I comment the constructor and use this version of the constructor everything is ok

  appointment::appointment(int d,int m,int y,string n) 
//date.day(d),date.month(m),date.year(y),name(n)
{
  date.day=d;
  date.month=m;
  date.year=y;
  name=n;
}

appointment 's constructor's member-initialiser can only initialise appointment 's own, direct members.

It cannot reach into those members and directly initialise their members.

It has to initialise date , not date 's members.

Now, date itself has no constructor, but it doesn't need one because you can use aggregate initialisation with it:

appointment::appointment(int d,int m,int y,string n)
    : date{d, m, y}
    , name(n)
{}

You did not encounter the problem with your second attempt, because that did not initialise anything! It merely provided a sequence of assignments (as made possible by the public interface of the Date type), and that's fine.

One might argue that this a limitation of the language, but I think it's sensible. You wouldn't want people to only half-initialise your classes. That could lead to inconsistent and unpredictable results.

You can't initialize objects piece by piece like that. Instead, use aggregate initialization to initialize your whole date member all in one go:

appointment::appointment(int d, int m, int y, std::string n)
    : date{d, m, y},
      name{n}
{
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM