例如这样的一个类:
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
};
迷茫2017-04-17 13:27:18
There are two methods, one is to use the constructor and/or assignment operator with parameters std::initializer_list
, and the other is that this class meets the conditions of aggregate class.
Using the constructor and/or assignment operator with parameters std::initializer_list
, any class can use this method. For example:
#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;
}
If a class meets the conditions of aggregate class, you can automatically use a brace list to initialize the members of the class.
For example, the following class satisfies the conditions of aggregate class:
struct C {
int i;
std::string s;
double d;
};
So it can be initialized as follows:
C c = { 10, "abc", 6.66 };
The conditions for a class to be an aggregate class are:
All non-static data members are public (public
)
does not define any constructor (but you can use = default
or = delete
)
No base class
No virtual member function
No in-class initialization (deprecated after C++14)
So, the subject’s class definitely does not meet this condition.