hello~ 很高兴见到大家! 这次带来的是C++中关于继承这部分的一些知识点,如果对你有所帮助的话,可否留下你宝贵的三连呢? 个 人 主 页: 默|笙

下面举一个例子:
class Person
{
public:
protected:
string _name = "小明";//名字
int _age = 18;//年龄
string _address;//地址
string _tel;//电话
};
class Student : public Person
{
public:
void study()
{
cout << "study()" << endl;
}
private:
string _stuid;//学号
};
class Teacher : public Person
{
public:
void teaching()
{
cout << "teaching()" << endl;
}
};class/struct 派生类 : 继承方式 基类

template<class T>
class stack : public vector<T>
{
public:
void push(const T& x)
{
vector<T>::push_back(x);//指定类域:vector<T>
}
void pop()
{
vector<T>::pop_back();
}
const T& top()
{
return vector<T>::back();
}
bool empty()
{
return vector<T>::empty();
}
};int d1 = 1;
double d2 = d1;//内置类型之间的隐式类型转换,值拷贝,临时值随后被销毁
const double& d3 = d1;//引用需要添加const,绑定临时对象,延长临时对象的生命周期
string s1 = "aaa";//构造(临时对象) + 拷贝构造(临时对象拷贝构造到s1),编译器优化为直接构造
const string& s2 = "aaa";//引用会省略拷贝构造,需要添加const来绑定临时对象
2.派生类对象和基类对象之间: 派生类对象可以赋值给基类对象,这通过基类的拷贝构造函数或赋值重载函数完成,这个过程就像是派生类里的基类之外的一部分被切掉了一样,只留下基类的一部分,所以也被叫做切割或切片。

观察以下代码:
class A
{
public:
void fun()
{
cout << "func()" << endl;
}
};
class B : public A
{
public:
void fun(int i)
{
cout << "func(int i)" <<i<<endl;
}
};
int main()
{
B b;
b.fun(10);
b.fun();
return 0;
};class Person
{
public:
Person(const char* name = "小明")
{
cout << "Person(const char* name) " << endl;
}
Person(const Person& p)
{
cout << "Person(const char& name)" << endl;
_name = p._name;
}
Person& operator=(const Person& p)
{
cout << "operator=(const Person& p)" << endl;
if (&p != this)
{
_name = p._name;
}
return *this;
}
~Person()
{
cout << "~Person()" << endl;
}
protected:
string _name;
};
class Student : public Person
{
public:
Student(const char* name = "xiaofang", int num = 1)
:Person(name)
,_num(num)
{
cout << "Student(const char* name, int num)" << endl;
}
Student(const Student& s)
:Person(s)//派生类对象赋值给基类引用
,_num(s._num)
{
cout << "Student(const Student& s)" << endl;
}
Student& operator=(const Student& s)
{
cout << "Student& operator=(const Student& s)" << endl;
if (this != &s)
{
Person::operator=(s);
_num = s._num;
}
}
~Student()
{
cout << "~Student()" << endl;
}
//派生类析构调用之后,会自动调用基类析构--当自己实现析构时不用显式调用基类析构
private:
int _num;
};
int main()
{
Student s;
return 0;
}
格式:
class/struct 类名称 final//在定义的时候今天的分享就到此结束啦,如果对读者朋友们有所帮助的话,可否留下宝贵的三连呢~~ 让我们共同努力, 一起走下去!