1、虚基类与虚继承
class A
{
public:
virtual void func()
{
cout << "call A ::func()" << endl;
}
void operator delete(void* ptr)
{
cout << "operator delete ptr " << ptr << endl;
free(ptr);
}
private:
int ma;
};
class B :virtual public A
{
public:
virtual void func()
{
cout << "call B ::func()" << endl;
}
void* operator new(size_t size)
{
void* p = malloc(size);
cout << "operator new p:" << p << endl;
return p;
}
private:
private:
int mb;
};
/*
A a;4
B b:8;ma,mb;
*/
int main()
{
//基类指针指向的派生类对象,永远指向派生类的地址
B b;
A* p = &b; //栈上自己会析构
//A* p = new B();
cout << "mian p :" << p << endl;
p->func();
//delete p;
return 0;
/*
vbptr
*p 释放了从这边开始 释放出错
vfptr
*/
}
2、菱形继承的问题
解决方法:虚继承
虚继承之后报错:
严重性 代码 说明 项目 文件 行 禁止显示状态 详细信息
错误 C2512 “A::A”: 没有合适的默认构造函数可用 Primer_cpp5 P:\qiniu_basic_learn\first_parase\Primer_cpp5\test.cpp 678
因为ma靠近d了,需要d自己初始化
代码:
/*多重继承
菱形继承的问题
*/
class A
{
public:
A(int data) :ma(data) { cout << "A()" << endl; }
~A() { cout << "~A()" << endl; }
protected:
int ma;
};
class B : virtual public A
{
public:
B(int data) :A(data), mb(data) { cout << "B()" << endl; }
~B() { cout << "~B()" << endl; }
protected:
int mb;
};
class C :virtual public A
{
public:
C(int data) :A(data), mc(data) { cout << "C()" << endl; }
~C() { cout << "~C()" << endl; }
protected:
int mc;
};
class D :public B, public C
{
public:
D(int data) :A(data), B(data), C(data), md(data) { cout << "D()" << endl; }
~D() { cout << "~D()" << endl; }
protected:
int md;
};
int main()
{
D d(10);
return 0;
}
3、四种类型的转换
class Base
{
public:
virtual void func() = 0;
};
class Derive1 :public Base
{
public:
void func() { cout << "call Dervivel::func" << endl; }
};
class Derive2 :public Base
{
public:
void func() { cout << "call Derive2::func" << endl; }
//sDerive2实现新功能的API接口函数
void derive02func()
{
cout << "call Derive2::derive02func" << endl;
}
};
void showFunc(Base* p)
{
//dynamic_cast会检查p是否指向的是一个Derive2类型的对象
//p->vfptr->vftable RTTI信息 如果是,dynamic_cast转型成功
//返回Derive2对象的地址,给p2,否则返回nullptr
Derive2* p2 = dynamic_cast<Derive2*>(p);
if (p2 != nullptr)
{
p2->derive02func();
}
else
{
p->func(); //动态绑定 *p的类型 Derive2 derive02func
}
}
int main()
{
Derive1 d1;
Derive2 d2;
showFunc(&d1);
showFunc(&d2);
//const int a = 10;
//int* p1 = (int*)&a;
//int* p2 = const_cast<int*>(&a);
//cout << *p2 << endl;
//int b = const_cast<int>(a); 不支持必须是指针或者引用类型
//int& b = const_cast<int&>(a);
//cout << b << en dl;
/*int a = 95;
char b = static_cast<int>(a);
cout << b << endl;*/
//基类 《=》派生类 能不能用static_cast
//int* p = nullptr;
//double* b = (double*)p;
return 0;
}