C 帮助类继承
C++ help class inheritance
我已经完成了一个父级和一个继承的类。在我给继承的类的主要目的的主要中,错误会出现错误,例如"对象无法访问"。这是我的代码
#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
相关文章:
- 继承函数的重载解析
- 继承期间显示未知行为的子类
- 需要帮助设置在C++中使用的Potrace
- 头文件-继承c++
- 在指针的帮助下,文本文件中单词的频率
- 为什么在保护模式下继承升级不起作用
- 通过继承类使用来自不同命名空间的运算符
- 子目录是否继承属性,例如add_definitions,include_directories和父Cmakelist.t
- 混合组合和继承的C++问题
- 继承:构造函数,初始化C++11中基类的类C数组成员
- 计算每个节点的树高,帮助我解释这个代码解决方案
- 从类继承时,继承的类是否会通过父类重新定义继承的变量
- 需要一些帮助了解私人 /保护 /公共继承
- 需要一些帮助来理解类继承(C++)
- 在使用类继承时需要帮助C++
- C 帮助类继承
- 需要对多个类之间继承的C 代码进行帮助重组和/或重新编写此C 代码
- 请帮助在继承 #constructor_error 上调试此 c++ 代码
- 虚拟公共继承?需要帮助理解代码
- D&D 游戏的类、命名空间和继承帮助