c++ - 调用父类(super class)函数继承c++

标签 c++ oop inheritance

在我的 C++ 文件中,当我运行 visual studio 时,我的输出不是我想的那样,我不知道我在哪里搞砸了。基本上我有一个 Person 和一个 Student 类,student 类继承自 Person 类,当创建 student obj 时,它调用 Person 类来初始化 common变量。

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;

}

我的输出是 I am a person。 -858993460 这是为什么?

最佳答案

您调用父类(super class)的构造函数的方式是错误的。你应该这样做:

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

请注意,当您将 Person(_name, _age); 放入正文中时,除了构造一个临时的 Person 对象外,它没有任何作用。另一方面,上面的正确方法引用了要使用这些参数构造的“嵌入式”Person

关于c++ - 调用父类(super class)函数继承c++,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42239929/

相关文章:

c++ - Qt 中的小部件 : Change background-color onclick

python - 构造函数 B 未在 A -> B -> C 继承链中调用

javascript - 如何扩展继承Backbone.Events的类?

c++ - 理解这个复杂的声明

C++ sqrt 返回 -1.#IND000000000000

c++ - TableView : go to new line at the end of the window

php - 用于 PHP 中静态属性的魔术 __get getter

php - "Inline"PHP 中的类实例化? (为了便于方法链接)

c++ - virtual 关键字会影响基类方法的性能吗?

database - 基于Postgresql继承的数据库设计