当我包含child.h并生成一个子变量时,它说没有为子项存在默认构造函数?顺便说一句是这样的:
Child::Child(const Child& otherChild) {
this->name = otherChild.GetName();
}
Run Code Online (Sandbox Code Playgroud)
制作复制构造函数的正确方法.我可以将指针传入此复制构造函数吗?或者如果我想传入一个指针,它应该是这样的:
Child::Child(const Child *otherChild) {
this->name = otherChild->GetName();
}
Run Code Online (Sandbox Code Playgroud)
父:
#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;
};
Run Code Online (Sandbox Code Playgroud)
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;
}
Run Code Online (Sandbox Code Playgroud)
标题:
#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;
};
Run Code Online (Sandbox Code Playgroud)
所述Child类只能通过提供参数给一个构造函数来构造; 你还没有提供没有参数的"默认构造函数".因此,Parent类的每个构造函数都需要提供参数来初始化其Child成员.您需要在构造函数的主体实际开始运行之前执行此操作,因此C++具有特殊的语法.它看起来像这样:
Parent::Parent(std::string name)
: myChild("childname")
{
}
Run Code Online (Sandbox Code Playgroud)
您可能想重新考虑您的类结构,因为它现在的方式,每个Parent对象必须有一个Child; 你真的没办法表达没有孩子的父母.