首页 > c++中自定义的类怎么使用大括号进行赋值

c++中自定义的类怎么使用大括号进行赋值

例如这样的一个类:

class myMatrix {
public:
    myMatrix(int row,int col);
private:
    int row;
    int col;
    double *pData;
};  

有没有办法实现如下样子的赋值?

myMatrix m(3,3) = {
    1,2,3
    4,5,6
    7,8,9
};

用initializer_list


有两种方法,一是使用参数为std::initializer_list的构造函数和/或赋值运算符,二是这个类满足 aggregate class 的条件。

方法一

使用参数为std::initializer_list的构造函数和/或赋值运算符,任意类都可以使用这个方法。例如:

#include <initializer_list>
#include <iostream>

// 没有考虑各种边界问题,仅为示意
class myMatrix {
public:
  myMatrix(int r, int c)
     : row(r), col(c) { pData = new double[row * col]; }
  myMatrix(int r, int c, std::initializer_list<double> il)
     : myMatrix(r, c) { *this = il; }
  ~myMatrix() { delete[] pData; }
  // Other four copy-control members are omitted here.
  myMatrix &operator=(std::initializer_list<double> il) {
    std::size_t pos = 0;
    for (const auto &e : il)
      pData[pos++] = e;
    return *this;
  }
  double get(int r, int c) const { return pData[r * col + c]; }
private:
  int row;
  int col;
  double *pData;
};

int main() {
  myMatrix m1(3, 3);
  m1 = {
    1, 2, 3,
    4, 5, 6,
    7, 8, 9
  };
  std::cout << m1.get(2, 2) << std::endl;  // 9

  myMatrix m2(4, 2, {
    11, 22,
    33, 44,
    55, 66,
    77, 88
  });
  std::cout << m2.get(2, 0) << std::endl;  // 55

  return 0;
}

方法二

类满足 aggregate class 的条件,则自动可以使用大括号列表来初始化类的成员。

例如下面的类满足 aggregate class 的条件:

struct C {
  int i;
  std::string s;
  double d;
};

所以可以如下初始化:

C c = { 10, "abc", 6.66 };

一个类是 aggregate class 的条件是:

所以,题主的类肯定不符合这个条件。

【热门文章】
【热门文章】