1.直接继承父类的方法
#include <iostream>
#include <string>
using namespace std;
class Person{
public:
void eat(){
cout<<"在吃饭"<<endl;
}
};
class Student : public Person{
private:
int age;
public:
string name;
Student() {
cout << "无参数构造函数" << endl;
}
};
int main() {
Student student;//创建一个名为student的Student类的对象
student.eat();
return 0;
}
2.重载
重载就是让同一个函数名可以有不同的参数列表,就像一个多功能工具一样🛠️
#include <iostream>
#include <string>
using namespace std;
class Person{
public:
void eat(){
cout<<"在吃饭"<<endl;
}
};
class Student : public Person{
private:
int age;
public:
string name;
Student() {
cout << "无参数构造函数" << endl;
}
void eat(string food) {
cout << "在吃" << food << endl;
}
};
int main() {
Student student;//创建一个名为student的Student类的对象
student.eat("馒头");
return 0;
}
在 C++ 中,如果类中没有定义任何构造函数,那么编译器会自动生成一个默认的无参构造函数。
这个默认的无参构造函数会进行一些基本的初始化操作,例如将类的数据成员初始化为默认值等。但是,如果类中已经定义了一个或多个构造函数,那么编译器通常不会再自动生成默认的无参构造函数。