【发布时间】:2021-05-30 11:42:02
【问题描述】:
请帮助我。我想在组合/整个类的成员初始化器列表中初始化“部分”类的数组。 这里 B 类由 A 类组成。现在在 B 类构造函数中,我将如何初始化成员初始化器列表中的数组。我知道如何在整个类的构造函数中初始化“部分”类的单个对象,但是如何在整个类的构造函数中初始化部分类的数组。 另外,如果我不在成员初始化程序列表中初始化零件类的数组,代码会起作用吗?提前致谢。
#include <iostream>
using namespace std ;
class A //part class
{
public:
A( int value = 0)
{ a = value ; }
void printA()
{
cout << "\nPrinting A members : " << a << endl ;
}
void setA( int value)
{ a = value ; }
protected:
int a ;
};
class B //whole class
{
public:
B( int value = 5 ) : aM(0) //member initializer list
{ b = value ; }
void printB()
{
cout << "\nPrinting B members : " << b << endl ;
aM.printA() ;
for (int i = 0 ; i < 5 ; i++)
cout << arr[i] << " , " ;
}
private:
int b ;
A aM ; //composition
A arr[5] ;
};
int main()
{
B objB ;
objB.printB() ;
return 0 ;
}
【问题讨论】:
标签: c++ class operator-overloading composition initializer-list