【发布时间】:2015-03-12 01:12:17
【问题描述】:
我目前正在处理一项任务,以扩展我们之前制作的程序,涉及头文件和父类的使用。在原始文件中,我有 2 个头文件。 Person.h 和 OCCCDate.h。在新的文件中,我正在创建一个名为 OCCCPerson.h 的文件。这是一个非常简单的类,基本上只使用 Person,只添加了 1 个变量。
我的问题是,我不知道如何正确使用父构造函数。
这是 Person.h 文件。
#ifndef PERSON_H
#define PERSON_H
#include <string>
#include "OCCCDate.h"
using namespace std;
class Person{
private:
string firstName;
string lastName;
OCCCDate dob;
public:
Person();
Person(string, string);
Person(string, string, OCCCDate);
string getFirstName();
string getLastName();
void setFirstName(string);
void setLastName(string);
int getAgeInYears();
bool equals(Person);
string toString();
};
#endif
这是我的 OCCCPerson.h 文件
#ifndef OCCCPERSON_H
#define OCCCPERSON_H
#include <string>
#include "OCCCDate.h"
#include "Perosn.h"
using namespace std;
class OCCCPerson : Person{
protected:
string studentID;
public:
OCCCPerson(string firstName, string lastName, OCCCDate dob, string studentID);
OCCCPerson(Person p, string studentID);
string getStudentID();
bool equals(OCCCPerson p);
string toString();
};
#endif;
我似乎无法调用父母构造函数来获取名字、姓氏和 dob(出生日期)等信息。从我的讲义中,它说父构造函数必须初始化为:Person(parameters),其中参数是父类中的东西。但是,我不知道该放在哪里。抱歉写了这么多。我只是不知道如何缩小它。
哦,这里是 OCCCDate.h 以防万一
#ifndef OCCCDATE_H
#define OCCCDATE_H
#include<string>
using namespace std;
class OCCCDate{
private:
bool OCCCDate_US;
bool OCCCDate_EURO;
int dayOfMonth, monthOfYear, year;
bool dateFormat;
public:
OCCCDate();
OCCCDate(int dayOfMonth, int monthOfYear, int year);
int getDayOfMonth();
int getMonth();
string getNameOfMonth();
int getYear();
string getDate();
int getDifference(OCCCDate d1, OCCCDate d2);
int getDifference(OCCCDate d1);
void setDateFormat(bool);
bool equals(OCCCDate d);
string toString();
};
#endif
这是我的 OCCCDate.cpp 文件
#include<iostream>
#include<ctime>
#include "OCCCPerson.h"
using namespace std;
OCCCPerson::OCCCPerson(string firstName, string lastName, OCCCDate dob, string studentID):Person(firstName, lastName, dob){
string firstName = Person::getFirstName();
string lastName = Person::getLastName();
OCCCDate dob = dob;
this->studentID = studentID;
}
OCCCPerson::OCCCPerson(Person p, string studentID){
Person p = p;
this->studentID = studentID;
}
【问题讨论】:
-
通过 const 引用传递字符串。如果你要返回一个字符串成员,你可以通过 const 引用返回它。
标签: c++ inheritance constructor parent-child