【问题标题】:I want to initialize an array of "part" class in member initializer list of composed/whole class我想在组合/整个类的成员初始化器列表中初始化“部分”类的数组
【发布时间】: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


    【解决方案1】:

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

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

    另一方面,

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

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

    arr[i].printA();
    

    【讨论】:

      【解决方案2】:

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

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

      不过写就够了

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

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

      如果你想使用数组的初始化器而不是零,那么你可以写例如

      B( int value = 5 ) : b( value ), aM(0), 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 ;
      
       };
      

      【讨论】:

        猜你喜欢
        • 2016-08-19
        • 2015-02-07
        • 2023-03-13
        • 2015-11-28
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2019-09-10
        • 2010-11-10
        相关资源
        最近更新 更多