gpt4 book ai didi

c++ - 默认构造函数全部封装在头文件中

转载 作者:太空宇宙 更新时间:2023-11-04 12:16:04 25 4
gpt4 key购买 nike

今天在我的课上,我们进行了继承练习。我们要编写一个继承自 Student 类的 UnderGrad 类,而 Student 类继承自 Person 类。

Person 类有 3 个变量,一个是名字,一个是地址,一个是生日。

学生有一个 ID 号、专业和学位类型。

最后,本科生有一个以前的高中和学分获得变量。

当我为每个类编写头文件时,默认构造函数如下所示:

   //snippet from UnderGrad.h
Undergrad(string nm = "", string add = "", string bday = "", int id = 0, string maj = "", string degtyp = "", string hs = "", int cred = 0) : Student(nm,add,bday,id,maj,degtyp) {

highSchool = hs;
credits = cred;
};


//snippet from Student.h
Student(string nm = "", string add = "", string bday = "", int id = 0, string maj = "", string degtyp = "") : Person(nm,add,bday){
stuId = id;
major = maj;
degreeType = degtyp;
};

//snippet from Person.h
Person(string nm = "", string add = "", string bday = ""){
name = nm;
address = add;
bDay = bday;
};

我的教授说这是不可读的,而且它不是真的这样做的。

我想知道,以这种方式创建默认构造函数有什么问题?有什么不对的吗?有更好的方法吗?

最佳答案

如果没有代码上下文的好处,我只会对这些构造函数进行一些更改。

  1. 我会考虑将构造函数的定义移动到单独的源文件中。这将允许在不触发重新编译其余代码的情况下更改定义。对于小程序或非常简单的构造函数,如果不更改 header 就不太可能更改,这可能不值得付出努力。

  2. 我会更改构造函数的定义以使用成员初始化列表,而不是在构造函数主体中分配成员。 (有关解释,请参阅 Als 的回答)。

  3. 我会删除函数定义末尾的分号,它们完全不需要。

  4. 我会将长构造函数分成几行,以避免代码行过长(长行可能不适合您的编辑器,并且可能难以执行差异和合并)。

  5. 您的头文件中似乎有一个using namespace::std 或一个using::std::string。这是不好的做法,因为这意味着包含您的 header 的代码将应用此 using。这可能会使客户端代码的含义发生变化,或者使客户端代码变得模棱两可而无法编译。我会删除 using,而是使用 std::string 的限定名称。


这些改变付诸行动:

//snippet from UnderGrad.h
Undergrad(
std::string nm = "",
std::string add = "",
std::string bday = "",
int id = 0,
std::string maj = "",
std::string degtyp = "",
std::string hs = "",
int cred = 0) :
Student(nm,add,bday,id,maj,degtyp),
highSchool(hs),
credits(cred)
{
}

//snippet from Student.h
Student(
std::string nm = "",
std::string add = "",
std::string bday = "",
int id = 0,
std::string maj = "",
std::string degtyp = "") :
Person(nm,add,bday),
stuId(id),
major(maj),
degreeType(degtyp)
{
}

//snippet from Person.h
Person(std::string nm = "", std::string add = "", std::string bday = "") :
name(nm), address(add), bDay(bday)
{
}

关于c++ - 默认构造函数全部封装在头文件中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7656565/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com