c++ - 继承和少量参数

标签 c++ inheritance parameters

Bob 叔叔在他的干净代码中建议函数 get 的参数不应超过 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/

相关文章:

java - 重写 Java 中的构造函数

objective-c - NSString(或 NSArray 或其他)到 C (char *) 字符串的可变参数列表

ruby-on-rails - 将 post 请求表单数据传递给 Rails Controller

c++ - 'if' 表达式后续变量声明

c++ - 使用 boost::property_tree::ptree 如何获取特定键的值

c++ - 如何使用 painter 类绘制 svg 图形

java - 具有继承的静态 block 的行为

c++ - 这段关于 scanf 的代码是什么?

c# - 关于 .NET 框架中继承的一般问题

ios - 如何在 iphone iOS 中使用参数在 SQLITE 中形成 LIKE 语句?