简体   繁体   中英

No default constructor exists for child - c++

When I include child.h and make a variable of child it say no default constructor exists for child? Btw am is this:

Child::Child(const Child& otherChild) {
    this->name = otherChild.GetName();
}  

the right way to make a copy constructor. And can I pass in a pointer into this copy constructor? Or should it be like this if I want to pass in a pointer:

Child::Child(const Child *otherChild) {
    this->name = otherChild->GetName();
}  

parent:

#pragma once

#include <string>
#include <ostream>
#include "Child.h"

using namespace std;

class Parent {
public:
    Parent(string name);
    Parent(const Parent& otherParent);
    friend ostream& operator<<(ostream & os, const Parent& parent);
    Parent operator=(const Parent& otherParent) const;
    string GetParentName() const;
    Child GetChild() const;

private:
    string name;
    Child myChild;

};

cpp:

#include "Child.h"

Child::Child(string name) {
    this->name = name;
}

Child::Child(const Child& otherChild) {
    this->name = otherChild.GetName();
}

string Child::GetName() const
{
    return name;
}

header:

#pragma once

#include <string>
#include <ostream>

using namespace std;

class Child {
public:
    Child(string name);
    Child(const Child& otherChild);
    string GetName() const;

private:
    string name;
};

The Child class can only be constructed by supplying arguments to a constructor; you have not provided a "default constructor" with no arguments. Therefore, every constructor of your Parent class needs to provide arguments to initialize its Child member. You need to do it before the body of the constructor actually starts running, so C++ has a special syntax for that. It would look something like this:

Parent::Parent(std::string name)
  : myChild("childname")
{
}

You might want to reconsider your class structure, since the way it is right now, every Parent object must have a Child ; you don't really have a way to express childless parents.

The class Parent has data member of the type Child

class Parent {
public:
    Parent(string name);
    Parent(const Parent& otherParent);
    friend ostream& operator<<(ostream & os, const Parent& parent);
    Parent operator=(const Parent& otherParent) const;
    string GetParentName() const;
    Child GetChild() const;

private:
    string name;
    Child myChild;
    ^^^^^^^^^^^^^
};

And for this data member there is called the default constructor because it seems you do not initialize the data member in the mem-initializer-list of the Parent constructor.

You need to initialize it something lie

Parent::Parent(string name) : myChild( SomeValue )
{
    //...
}

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