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

浏览:28日期:2023-05-18

问题描述

例如这样的一个类:

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

问题解答

回答1:

有两种方法,一是使用参数为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 的条件是:

所有的非常量数据成员(non-static data member)是公有的(public)

没有定义任何构造函数(但可以使用= default或= delete)

没有基类

没有虚成员函数

没有类内初始化(C++14后废除)

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

回答2:

用initializer_list

相关文章: