关于继承的成员的有关问题
关于继承的成员的问题子类不能直接使用父类的成员吗?比如初始化成员变量?C/C++ codeclass Student{public:
关于继承的成员的问题 子类不能直接使用父类的成员吗?比如初始化成员变量?
C/C++ codeclass Student{public: Student() : name("Student"), sex('M'), age(18), num("1") {} Student(string n, char s, int a, string no) : name(n), sex(s), age(a), num(no) {}protected: int age; string name; char sex; string num;};class CollegeStudent : public Student{public: CollegeStudent(string n, char s, int a, string no) : name("CollegeStudent") {}}; 编译器在子类那name那里提示错误,说是“name不是类CollegeStudent的非静态数据成员或基类”,这是咋回事?
我的理解是,子类继承了基类的非protected变量,作为自己的成员变量来用,可以这样不?
[解决办法] 不行.
对于类CollegeStudent构造时你这样的写法相当于
先调用父类构造函数
Student();
然后调用
CollegeStudent(string n, char s, int a, string no);
如果要达到你那样的要求,需要
CollegeStudent(string n, char s, int a, string no):Student("CollegeStudent",....){}
[解决办法] 貌似初始化列表只能初始化自己的成员或者父类,对于父类成员则不行。
[解决办法] 探讨 引用: 子类不可以直接访问基类的数据成员,如果实在想要访问,只能通过调用基类的成员函数实现 .... 谁说不可以?赋值也算是访问吧? class CollegeStudent : public Student { public: CollegeStudent(string n, char s, int a, string no) {name="Coll……[解决办法] 探讨 引用: 子类不可以直接访问基类的数据成员,如果实在想要访问,只能通过调用基类的成员函数实现 .... 谁说不可以?赋值也算是访问吧? class CollegeStudent : public Student { public: CollegeStudent(string n, char s, int a, string no) {name="Coll……