Pointer - How to pass array in C++ initialization list?
巴扎黑
巴扎黑 2017-05-16 13:25:27
0
2
706

As shown in the title, X and Y in the code below can be constructed normally, but A and B report errors[Error] incompatible types in assignment of 'const int' to 'int []' .

Please tell me how to pass the array in the initialization list in the above situation.
in order to fulfill

  A a1({1});
  A a2({1, 2});
  A a3({1, 2, 3})

In this way, member variables are initialized with an array of any size.

#include <iostream>
using namespace std;

class A {
public:
  A(const int*);

protected:
  int o[4];
};

class B : public A {
public:
  B(int, int);
};

class X {
public:
  X(int, int);

protected:
  int o[4];
};

class Y : public X {
public:
  Y(int, int);
};

A::A(const int *p) : o(p){};

B::B(int p0, int p1) : A({p0, p1}){};

X::X(int p0, int p1) : o({p0, p1}){};

Y::Y(int p0, int p1) : X(p0, p1){};

int main() {
  A a({1, 2});
  B b(3, 4);
  X x(5, 6);
  Y y(7, 8);
  // A a1({1});
  // A a2({1, 2});
  // A a3({1, 2, 3})
}
巴扎黑
巴扎黑

reply all(2)
黄舟

It is recommended to use std::vector<int>,构造函数接受const std::vector<int> &arr,拷贝用this->o = arr.

習慣沉默

This question can be transformed into: Which formal parameter forms can pass the initialization list?

Non-template:

  • void foo(T), void foo(const T &),当T可以用初始化列表拷贝初始化时。即初始化T x = {...};Legal.

  • void foo(std::initializer_list<T>)

Template:

  • template <class T> void foo(std::initializer_list<T>)

  • template <size_t N> void foo(const T (&)[N])

  • template <class T, size_t N> void foo(const T (&)[N]), this is said to be only available in C++17, but some compilers already support it.

Code sample, including several common situations where it is not possible.

Initialize array member variables: There seems to be no simple way to initialize array members in the initialization list. It is recommended to assign values ​​within the function body of the constructor. But it can be achieved using templates:

#include <cstddef>

#include <utility>

class A {
 public:
  template <class... Args>
  A(Args... args) : x_{args...} {}
  
  virtual void foo() {} // 阻止aggregate initialization
 private:
  int x_[4];
};

template <class T, class U, size_t... ints>
A FactoryImpl(const T &list, std::integer_sequence<U, ints...>) {
  return {list[ints]...};
}

template <class T, size_t N>
auto Factory(const T (&arr)[N]) {
  return FactoryImpl(arr, std::make_index_sequence<N>());
}

int main()
{
  A x = {1,2,3,4};
  A y = Factory({1,2,3,4});
  return 0;
}
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!