64,646
社区成员
发帖
与我相关
我的任务
分享
class A;
void fcn( A* );
class A
{
public:
virtual void f() = 0;
A() { fcn( this ); }
};
class B : A
{
void f() { }
};
void fcn( A* p )
{
p->f();
}
// The declaration below invokes class B's constructor, which
// first calls class A's constructor, which calls fcn. Then
// fcn calls A::f, which is a pure virtual function, and
// this causes the run-time error. B has not been constructed
// at this point, so the B::f cannot be called. You would not
// want it to be called because it could depend on something
// in B that has not been initialized yet.
B b;
class A : public B
{
public:
A(int a):B(a) // 这个地方就是所谓的初始化列表,在这里你看到调用了抽象类的构造函数
{ // A类继承了B中的数据成员a,但通过B的构造函数去初始化
}
void fun()
{
cout << a << endl;
}
};
#include <iostream>
using namespace std;
class B
{
protected:
int a;
public:
B(int a)
{
this->a = a;
}
virtual void fun() = 0;
virtual ~B()
{
}
};
class A : public B
{
public:
A(int a):B(a)
{
}
void fun()
{
cout << a << endl;
}
};
int main(void)
{
B* b = new A(10);
b->fun();
return 0;
}