C++带头文件的多层继承实现正确性及颜色设置方式咨询
代码问题修正与构造方式选择
一、现有代码中的错误点
- 枚举类定义不完整:缺少
enum class Color的声明,正确写法如下:enum class Color { RED = 1, BLUE = 2, GREEN = 3 }; - Parent类定义末尾缺少分号:C++类定义结束必须添加
;,修正后:class Parent { public: Parent (const std::string &name = "", Color color = Color::RED) : a_name(name) , a_color(color) {}; Color getcolor() const { return a_color; } protected: std::string a_name; Color a_color; }; // 此处添加分号 - Child类的成员名与初始化列表不匹配:头文件中protected成员为
number,但cpp初始化列表写的是a_number,需统一命名;同时初始化列表里的父类名小写parent错误,应使用类名大写Parent:// child.hpp修正 class Child : public Parent { public: Child(std::string name, Color color, int number = 0); protected: int a_number; // 统一为a_number }; // 添加分号 // child.cpp修正 Child::Child (std::string name, Color color, int number) : Parent(name, color) // 改为大写Parent , a_number(number) {} - Grandchild类的错误:
- 命名空间错误:
Std::string需改为std::string(小写s); - 构造函数参数默认值位置非法:C++中默认参数必须放在参数列表末尾,你写的
Color color = Color::RED在无默认值的int number前面,不符合语法; - 构造函数定义末尾缺少大括号,类定义末尾缺分号。修正后:
// Grandchild.hpp修正 class Grandchild : public Child { public: Grandchild(std::string name, Color color, int number, int age = 0); private: int a_age; }; // Grandchild.cpp修正 Grandchild::Grandchild (std::string name, Color color, int number, int age) : Child (name, color, number) , a_age(age) {} - 命名空间错误:
二、构造方式的选择
如果要为每个Grandchild指定不同颜色,必须选择第一种构造方式(修正参数默认值位置后)——让Grandchild的构造函数接收Color参数并传递给父类,这样才能为每个对象单独设置颜色。
你给出的第二种方式是在Grandchild构造函数里固定传递Color::RED给Child,所有Grandchild对象的颜色都会被强制设为红色,完全无法满足“为每个Grandchild指定颜色”的需求。
如果希望Grandchild有默认颜色,但又支持手动指定,可以把Color参数的默认值移到参数列表末尾,示例如下:
// Grandchild.hpp Grandchild(std::string name, int number, int age = 0, Color color = Color::RED); // Grandchild.cpp Grandchild::Grandchild (std::string name, int number, int age, Color color) : Child (name, color, number) , a_age(age) {}
这种写法既可以默认使用红色,也能在需要时传入自定义颜色。
内容的提问来源于stack exchange,提问作者Ruo
相关产品推荐
相关产品推荐

