简体   繁体   English

调用超类函数继承c ++

[英]Calling superclass function inheritance c++

In my C++ file, when I run it visual studio, my output is not what I thought it was be an I don't know where I messed up. 在我的C ++文件中,当我运行visual studio时,我的输出不是我认为的那样,我不知道我搞砸了哪里。 Basically I have a Person and a Student class, and the student class inherits from the Person class, and when the student obj is created, it calls the Person class to initialize common variables. 基本上我有一个Person和一个Student类,student类继承自Person类,当创建student obj时,它调用Person类来初始化公共变量。

class Person {
public:
    Person() {

    }
    Person(string _name, int _age) {
        name = _name;
        age = _age;
    }

    void say_stuff() {
        cout << "I am a person. " << name << age << endl;
    }

private:
    string name;
    int age;
};

class Student : public Person {
public:
    Student(string _name, int _age, int _id, string _school) {
        Person(_name, _age);
        id = _id;
        school = _school;
    }

private:
    string name;
    int age;
    int id;
    string school;

};



int main() {


    Student s1("john", 20, 123, "AAAA");
    s1.say_stuff();

    system("pause");
    return 0;

}

My output is I am a person. -858993460 我的输出是I am a person. -858993460 I am a person. -858993460 Why is this? I am a person. -858993460这是为什么?

The way you invoke the constructor of the super class is wrong. 调用超类的构造函数的方式是错误的。 This is how you should do it: 这是你应该这样做的:

Student(string _name, int _age, int _id, string _school) : Person(_name, _age) {
   id = _id;
    school = _school;
}

Note that, When you put Person(_name, _age); 注意,当你把Person(_name, _age); inside the body, it has no effect but to construct a temporary Person object. 在body中,它没有任何效果,只能构造一个临时的Person对象。 On the other hand, the correct way above references the "embedded" Person to be constructed with these parameters. 另一方面,上面的正确方法引用了用这些参数构造的“嵌入式” Person

Your Student constructor's syntax is wrong, for constructing it's superclass. 您的Student构造函数的语法错误,用于构造它的超类。 It should be: 它应该是:

Student(string _name, int _age, int _id, string _school)
        : Person(_name, _age) {

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

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