gpt4 book ai didi

c++ - 继承和少量参数

转载 作者:搜寻专家 更新时间:2023-10-31 00:29:55 26 4
gpt4 key购买 nike

Bob 叔叔在他的 Clean Code 中建议函数获取的参数不应超过 3 个:

Functions that take three arguments are significantly harder to understand than dyads. The issues of ordering, pausing, and ignoring are more than doubled. I suggest you think very carefully before creating a triad.

但是类继承层次结构中的 CTOR 参数呢?如果层次结构中的每个类都添加一个新字段并且您应该在 CTOR 中初始化它们会怎样。请参见下面的示例:

class Person
{
private:
std::string m_name;
int m_age;

public:
Person(const std::string& name, const int age);
std::string getName() const { return m_name; }
int getAge() const { return m_age; }
~Person();
};


class Student : public Person
{
private:
std::string m_university;
int m_grade;

public:
Student(const std::string& name, const int age, const std::string& university, const int grade);
std::string getUniversity() const { return m_university; }
int getGrade() const { return m_grade; }
~Student();
};

查看 Student 如何获得 4 个参数,而 Person 仅获得 2 个而 Student 又增加了两个。那么我们应该如何处理呢?

最佳答案

有几种方法。

Combine multiple parameters into a struct

struct PersonInfo {
std::string name;
int age;
};

struct StudentInfo {
PersonInfo person_info;
std::string university;
int grade;
};

Person::Person(const PersonInfo &info) :m_name(info.name), m_age(info.age) {}
Student::Student(const StudentInfo &info) : Person(info.person_info), m_university(info.university), m_grade(info.grade) {}

Default initialize data members and set them with setter utilities

Person::Person() : m_age(0) {}
void Person::set_age(int age) { m_age = age; }

Student() : m_grade(0) {} // Person is default constructed.
void Student::set_grade(int grade) { m_grade = grade; }

关于c++ - 继承和少量参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38969377/

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