在C++中,派生类在定义构造函数时,会调用基类构造函数首先完成基类部分的构造:
class Derive : public Base
{
public:
Derive(string nam, int ad, int elem):Base(elem) {
// 等价: this->name = nam;
// this->add = ad;
name = nam;
add = ad;
}
...
}
若若派生类定义了一个基类已有的数据成员,则会覆盖掉基类。在这个构造过程中,之类自身的成员构造可以使用this指针,
this->name = name;
也可以直接使用派生类自己已经定义的变量名进行赋值操作,如:
name = name1;
派生类只能直接访问基类中public/protected的成员,使用【基类类名::member】的形式:
class Derive: public Base{
int new_id = Base::id;// id 在Base中public或protected
string new_name= Base::getName(); //getName是Base的非private成员函数
...........
};
最后,一起看下完整代码:
#include <iostream>
using namespace std;
struct Base
{
public:
Base(int a) {
this->elem = a; // 等价: elem = a;
}
int getElem() {
return elem;
}
private:
int elem;
};
class Derive : public Base
{
public:
Derive(string nam, int ad, int elem):Base(elem) {
// 等价: this->name = nam;
// this->add = ad;
name = nam;
add = ad;
}
int getElem() {
return add + Base::getElem();
}
string getName() {
return name;
}
int getBaseElem(){
return Base::getElem();
}
private:
string name;
int add;
};
int main()
{
Derive d("child class object", 12, 15);
cout <<"Derive name="<< d.getName() << "\nDerive elem=" << d.getElem();
cout<<endl;
cout<<"Base elem="<<d.getBaseElem();
return 0;
}
下面是运行结果:
$g++ -std=c++11 -o main *.cpp
$main
Derive name=child class object
Derive elem=27
Base elem=15