1.基础的继承规则:
摘自:https://www.cnblogs.com/metalsteel/p/6280389.html
其中,传入名字的代码,应该加const定义,别的部分没有变化。
#include <iostream>
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
using namespace std;
class Parent
{
protected:
char *str;
public:
Parent(const char *stre)
{
if(str != NULL){
//存储这堆中,在类销毁时需要手动释放。
this->str = new char[strlen(str) + 1];
strcpy(this->str, str);
}
else{
this->str = NULL;
}
std::cout << "father create ... " << std::endl;
}
~Parent()
{
if(this->str != NULL)
{
//delete 数组类型
delete[] this->str;
this->str = NULL;
}
std::cout << "father destory ... " << std::endl;
}
};
class Object
{
private:
int i;
public:
Object(int i)
{
this->i = i;
std::cout << "Object create ... " << std::endl;
}
~Object()
{
//if need?
this->i=0;
std::cout << "Object destory " << std::endl;
}
};
class Child:public Parent
{
private:
Object obj;
char *name;
int age;
public:
//在构造子类对象时,要先调用父类的构造函数
Child():Parent(NULL),obj(10)
{
this->name = NULL;
this->age = 0;
std::cout <<"child create, no para" << std::endl;
}
Child(const char *name, int age):Parent(name),obj(age)
{
this->name = new char [strlen(name) + 1];
strcpy(this->name , name );
std::cout << "child create, has para" << std::endl;
}
~Child()
{
//c++ 判断字符串是否为空
// != NULL or !this->name
if(this->name != NULL)
{
delete [] this->name;
this->name = NULL;
}
std::cout << "child destory " << std::endl;
}
};
int main(int argc, char *argv[])
{
Child c1;
//类似这种固定的字符串,我们一定要定义成const, 不然会有warning。
//char *name="wanggang";
const char *name ="wanggang";
Child c2(name, 22);
return 0;
}
运行结果:
father create ...
Object create ...
child create, no para
father create ...
Object create ...
child create, has para
child destory
Object destory
father destory ...
child destory
Object destory
father destory ...
二、类的兼容性
class MyChild:public MyParent
{
protected:
int i;
public:
MyChild()
{
i=0;
name = "I'am Child";
}
};
int main(int argc, char *argv[])
{
MyChild c;
c.print();
MyParent p1=c;
p1.print();
MyParent *p2 = &c;
p2->print();
MyParent &p3 = c;
p3.print();
return 0;
}
运行结果:
ame is:= I'am Child
name is:= I'am Child
name is:= I'am Child
name is:= I'am Child
解释:
- 子类对象可以当做父类对象来使用。
- 子类对象可以直接赋值给父类对象。
- 子类对象可以直接初始化父类对象。
- 父类指针可以直接指向子类对象。
- 父类引用可以直接引用子类对象。
其实,个人理解就是包含关系,和防止空指针。
多重继承二义性:
#include <iostream>
using namespace std;
class B
{
public:
int a;
};
class B1 : virtual public B
{
};
class B2 : virtual public B
{
};
class C :public B1, public B2
{
};
int main(int argc, char *argv[])
{
C c;
//error
//error: cannot use dot operator on a type
//c.B::a = 100;
c.B::a = 100;
#if 1
printf("C.B::a :=%d \n", c.B::a);
printf("C.B1::a :=%d \n", c.B1::a);
printf("C.B2::a :=%d \n", c.B2::a);
#endif
}
运行结果:
C.B::a :=100
C.B1::a :=100
C.B2::a :=100