简体   繁体   English

如何在子类c ++的构造函数中设置基类的属性

[英]How to set an attribute of a base class in a constructor of a sub class c++

I have the following constructor in a class Student that is a subclass of a base class Person :我在Student类中有以下构造函数,它是基类Person的子类:

namespace Uni
{
    Uni::Student::Student(string majorCourse, int enrollNumber , string name, int age, bool isStudying)
        : Uni::Person::Person(std::__1::string name, int age, bool isStudying), majorCourse_(majorCourse), enrollNumber_(enrollNumber)    
    {
        cout << "[Temp] Student Default Constructor" << endl;
    }
    ...
}

I would like to set the attributes name_ , age_ and isStudying_ (which are attributes of the Person class) to the values of name , age , and isStudying , but I get an error on this statement:我想将属性name_age_isStudying_ (它们是Person类的属性)设置为nameageisStudying的值,但我在此语句中遇到错误:

Uni::Person::Person(std::__1::string name, int age, bool isStudying)

type name is not allowed不允许类型名称

How can I fix this?我怎样才能解决这个问题?

You should just be forwarding the arguments along to the base class, so lose the typenames您应该只是将参数转发到基类,因此丢失类型名

 Uni::Student::Student(string majorCourse, int enrollNumber , string name, int age, bool isStudying)
  : Uni::Person::Person(name, age, isStudying),
    majorCourse_(majorCourse),
    enrollNumber_(enrollNumber)
 { }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM