note: 'person::person()' is implicitly deleted because the default definition would be ill-formed

后端 未结 2 775
无人共我
无人共我 2020-12-30 20:44

I\'m working on an example program to help me learn structs in C++. Here\'s my code:

#include 
#include 
#include 

        
相关标签:
2条回答
  • 2020-12-30 21:17

    Well, the problem is not with that "note". The "note" simply explains the reason for the error. The error is that you are trying to default-construct your person object when class person does not have a default constructor.

    Instead of trying to default-construct it, you can {}- initialize that const member and the code will compile

    person bob = { nextPersonID++, "Bob", {}, 1 };
    bob.birthdate.day = 1;
    bob.birthdate.month = 1;
    bob.birthdate.year = 1990;
    ...
    

    Alternatively, you can simply write your own default constructor for the class.

    0 讨论(0)
  • 2020-12-30 21:17

    The problem has not to do with a "default-construct ... when class person does not have a default constructor." The problem has to do with having a constant in the declaration of the class and a constructor that does not guarantee that the constant will be defined. Suggest using an "initializer list".

    struct Person {
            int id;
            string name;
            date birthdate;
            const int numberOfAddresses;
            address addresses [1];
    
            Person(int); // constructor declaration
            Person() : numberOfAddresses(1) {} // constructor definition.
                          // ": numberOfAddresses(1)" is the initializer list
                          // ": numberOfAddresses(1) {}" is the function body
        };
        Person::Person(int x) : numberOfAddresses(x) {} // constructor definition. ": numberOfAddresses{x}" is the initializer list
        int main()
        {
            Person Bob; // calls Person::Person()
            Person Shurunkle(10); // calls Person::Person(int)
        }
    
    0 讨论(0)
提交回复
热议问题