本文主要是介绍“最晚辈派生”类和虚基初始化,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
如果虚基类存在一个构造函数, 虚基类的使用并不是很简单。为了便于理解,引入一个新术语:最晚辈派生类(most-derived)。
见下面代码:
#include < iostream >
using namespace std;
class base
{
protected:
int a;
public:
base(int aa) // constructor
{
a=aa;
}
} ;
class derivedA: virtual public base
{
protected:
int b;
public:
derivedA(int aa, int bb):base(aa) // constructor
{
b=bb;
}
void show()
{
cout<<a<<endl;
cout<<b<<endl;
}
} ;
class derivedB: virtual public base
{
protected:
int c;
public:
derivedB(int aa, int cc):base(13) // constructor
{
c=cc;
}
void show()
{
cout<<a<<endl;
cout<<c<<endl;
}
} ;
class AB: public derivedA, public derivedB
{
public:
AB(int aa, int bb, int cc) : derivedA(aa, bb), derivedB(aa, cc), base(33) {} // constructor
void show()
{
cout<<a<<endl;
cout<<b<<endl;
cout<<c<<endl;
}
} ;
int main()
{
derivedA aa(1, 2);
aa.show(); cout<<endl;
derivedB bb(3, 4);
bb.show(); cout<<endl;
AB ab(5, 6, 7);
ab.show();
return 0;
}
using namespace std;
class base
{
protected:
int a;
public:
base(int aa) // constructor
{
a=aa;
}
} ;
class derivedA: virtual public base
{
protected:
int b;
public:
derivedA(int aa, int bb):base(aa) // constructor
{
b=bb;
}
void show()
{
cout<<a<<endl;
cout<<b<<endl;
}
} ;
class derivedB: virtual public base
{
protected:
int c;
public:
derivedB(int aa, int cc):base(13) // constructor
{
c=cc;
}
void show()
{
cout<<a<<endl;
cout<<c<<endl;
}
} ;
class AB: public derivedA, public derivedB
{
public:
AB(int aa, int bb, int cc) : derivedA(aa, bb), derivedB(aa, cc), base(33) {} // constructor
void show()
{
cout<<a<<endl;
cout<<b<<endl;
cout<<c<<endl;
}
} ;
int main()
{
derivedA aa(1, 2);
aa.show(); cout<<endl;
derivedB bb(3, 4);
bb.show(); cout<<endl;
AB ab(5, 6, 7);
ab.show();
return 0;
}
输出
1
2
13
4
33
6
7
最晚辈派生类是当前所在的类,当考虑构造函数时它尤其重要。
在前面的例子中,基构造函数里的最晚辈派生类是base;
在derivedA构造函数中,derivedA是最晚辈派生类;
在AB构造函数中, AB是最晚辈派生类。
打算使用一个虚基类时,最晚辈派生类的构造函数的职责是对虚基类进行初始化。
这意味着该类不管离虚基类多远,都有责任对虚基类进行初始化。
参考: 《Thinking in C++》
width="728" scrolling="no" height="90" frameborder="0" align="middle" src="http://download1.csdn.net/down3/20070601/01184120111.htm" marginheight="0" marginwidth="0">
这篇关于“最晚辈派生”类和虚基初始化的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!