C 帮助类继承

C++ help class inheritance

本文关键字:继承 帮助      更新时间:2023-10-16

我已经完成了一个父级和一个继承的类。在我给继承的类的主要目的的主要中,错误会出现错误,例如"对象无法访问"。这是我的代码

#include <iostream>
#include <string>
using namespace std;
class Parents{
protected:
    int age;
    string name;
public:
    void getInfo(int hAge, string hName)
    {
        name = hName;
        age = hAge;
        cout << "Their son name is " << name << endl;
        cout << "He is " << age << " years old" << endl;
        cout << "His hair is red" << endl;
        cout << "He is a boy" << endl;
    }
};
class Son : public Parents{
    Son(){
        name = "John";
        age = 25;
    }
};

int main(){
    Son boy; //object not accessible
    system("pause");
    return 0;
}

班级儿子的构造函数默认为私有。公开。

class Son : public Parents{
public:
    Son(){
        name = "John";
        age = 25;
    }
};

更新:

class Parents{
protected:
    int age;
    string name;
public:
    // Call this when you have not already assigned value to age and name
    void getInfo(int hAge, string hName)
    {
        name = hName;
        age = hAge;
        cout << "Their son name is " << name << endl;
        cout << "He is " << age << " years old" << endl;
        cout << "His hair is red" << endl;
        cout << "He is a boy" << endl;
    }
    // Call this when age and name already have values.
    void getInfo()
    {
        cout << "Their son name is " << name << endl;
        cout << "He is " << age << " years old" << endl;
        cout << "His hair is red" << endl;
        cout << "He is a boy" << endl;
    }
};
class Son : public Parents{
public:
    Son(){
        name = "John";
        age = 25;
    }
};

int main(){
    Son boy; 
    boy.getInfo(); // Will call 2nd method
    boy.getInfo(13,"First method"); // will call 1st method
    system("pause");
    return 0;
}

Son的默认构造函数是私有的。因此,类别Son的对象不能像您在main函数中使用Son boy;尝试那样从班级外部构建。公开构造函数。

默认情况下,类内部的成员是 private 。因此,如果您想定义自己的构造函数并要访问它,则应将其指定为 public