我想在组合/整个类的成员初始化列表中初始化“部分”类的数组

问题描述

请帮我解决这个问题。我想在组合/整个类的成员初始值设定项列表中初始化“部分”类的数组。 这里 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 ;
}

解决方法

您初始化成员的数组与初始化数组几乎相同,使用花括号括起来的元素列表。如果您希望所有元素默认构造,或者什么都不做:

B( int value = 5 ) : b{ value },aM{ },arr{ }
{ }

另外一点,

cout << arr[i] << "," ;

无效,因为您没有用于 << 的重载 A 运算符。也许你想要这个:

arr[i].printA();
,

如果我理解正确,您需要的是以下内容

B( int value = 5 ) : b( value ),aM(0),arr{}
{
}

不过写就够了

B( int value = 5 ) : b( value )
{
}

因为类 A 的默认构造函数将用零初始化数据成员 aM 和 arr。

如果你想使用非零数组的初始值设定项,那么你可以写例如

B( int value = 5 ) : b( value ),arr{ 1,2,3,4,5}
{
}

和成员函数

 void printB()
 {
   cout << "\nPrinting B members : " << b << endl ;
   aM.printA() ;
   for (int i = 0 ; i < 5 ; i++)
     cout << arr[i] << "," ;
 }

不正确,因为没有为类型 A 的对象定义运算符

使本声明有效

     cout << arr[i] << "," ;

将操作符

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 ; }

    friend std::ostream & operator <<( std::ostream &os,const A &a )
    {
        return os << a.a;
    }
    protected:
      int a ;

 };