【问题标题】:Quick about C++ array class constructor快速了解 C++ 数组类构造函数
【发布时间】:2016-10-13 19:23:54
【问题描述】:

我正在尝试(强制)在另一个类中初始化一个由 3 个类元素组成的数组(我知道我可以使用向量和初始化列表,但我想知道是否有这种可能性),假设我有此代码为 ex:

class A{
 // CODE HERE, doesn't really matter
}

然后

class B{

string name;
A array[3]; <-- here's the point. I want array of 3 members of class A

public:

B(string name_, A a, A b, A c) : name(name_), array[0](a), array[1](b), array[2](c){} // Here's the problem. I can't initialize this way, it always give me some sort of error and array isn't recognized as a class variable (no color in the compiler like 'name' for ex shows and it should be).

 }

如果由于某种原因我没有在原型中初始化,而只是在函数内部进行,例如 this->array[0] = a 等等,它可以工作。但我想知道一种像上面显示的那样内联的方法。

【问题讨论】:

    标签: c++ arrays constructor initialization


    【解决方案1】:

    修复示例中的简单拼写错误后,您可以为数组使用大括号初始化列表,如下所示:

    class A{
     // CODE HERE, doesn't really matter
    };
    
    
    class B{
    
    string name;
    A array[3]; // <-- here's the point. I want array of 3 members of class A
    
    public:
    
    B(string name_, A a, A b, A c) : name(name_), array{a,b,c} {} 
                                                    // ^^^^^^^
    
     };
    

    See Live Demo

    此时无法通过索引取消引用。

    【讨论】:

      【解决方案2】:

      你可以在 C++11 中这样做

      class B{
          string name;
          A array[3]; 
      
      public:
      
          B(string name_, A a, A b, A c) 
              : name(name_),
              , array{a, b, c}
          {
          }
      };
      

      【讨论】:

        猜你喜欢
        • 2015-11-14
        • 2014-08-04
        • 1970-01-01
        • 2017-10-30
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2014-05-27
        相关资源
        最近更新 更多