C++: 继承
继承格式:
class 子类:继承权限:基类
{
};
当没有写继承权限时,继承权限默认为私有。
1.特点:
继承:
1.一个类自动拥有了来自另一个类的属性和方法
2.基类的处理构造和析构之外,其他的全盘继承**
基类的权限 public protected private——继承权限
public public protected private
protected protected protected private
private 不可访问 不可访问 不可访问
看代码理解:
class A
{
public:
int m_i;
void print() { cout << "A::print" << endl; }
protected:
int m_j;
private:
int m_k;
};
class B : public A
{
public:
void set()
{
m_i = 10;
m_j = 30;
//m_k = 40; //私有的能被继承,不能被访问
}
};
当sizeof(B)时,答案是12,因为继承关系,B类的内存单元有A类的数据成员。
因为继承权限是public,所以m_i和m_j可以被访问,而m_k不能被访问。
再来看一个:
class D :private A
{
public:
void fn()
{
m_i = 12;
m_j = 23;
//m_k = 34;
}
};
class DD :public D
{
public:
void ff()
{
/*m_i = 2;
m_j = 5;
m_k = 4;*/
}
};
D类被设定为私有基类,DD类继承权限是public
但是m_i,m_j,m_k都不能被访问,这是因为:
m_i,m_j,m_k三个数据成员先在D类被修饰成private,所以不管继承权限是什么都不能被访问
(看最上面的表格)
2.继承的步骤
继承三步骤:
1.除构造和析构全盘接收
2.改写
3.添加子类特有的
调用顺序:
有继承和组合的构造顺序—内存布局
1.先按照继承顺序调用基类的构造
2.按照组合顺序调用组合的构造
3.调用自己的构造
例如:
class A
{
public:
A() { cout << "A" << endl; }
~A() { cout << "~A" << endl; }
void print() { cout << "A::print" << endl; }
private:
int m_i;
};
class B :public A
{
public:
B() { cout << "B" << endl; }
~B() { cout << "~B" << endl; }
private:
int m_j;
};
void main()
{
B b;
}
问题
class Person
{
private:
int m_num;
char* m_name;
char m_sex;
}
class Student :public Person
{
private:
float m_score;
};
int main()
{
Student s1(1001, "wangpangpang", 'f', 89);
}
该怎样重载构造函数才能将这是个变量赋给S1?
答案:
class Person
{
public:
Person(int num,const char* name, char sex):m_num(num),m_sex(sex)
{
m_name = new char[strlen(name) + 1];
strcpy_s(m_name, strlen(name)+1, name);
}
~Person()
{
delete[]m_name;
m_name = NULL;
}
private:
int m_num;
char* m_name;
char m_sex;
};
class Student :public Person
{
public:
Student(int num, const char* name, char sex,float score):Person(num,name,sex),m_score(score)
{
}
private:
float m_score;
};
问题2
int main()
{
Student s2(s1);
s2.Print();
}
当一个对象给另一个对象赋值时,首先要想到调用拷贝构造函数,而系统自动调用的拷贝构造函数是浅拷贝,所以我们要自己写一个拷贝构造函数形成深拷贝
答案:
加上这两句
Person(Person& p) :m_num(p.m_num), m_sex(p.m_sex)//拷贝构造函数
{
m_name = new char[strlen(p.m_name) + 1];
strcpy_s(m_name, strlen(p.m_name) + 1, p.m_name);
}
Student(Student& s) :Person(s)
{
m_score = s.m_score;
}