tra*_*aww 0 c++ curly-braces parentheses
如何使用括号而不是花括号和等号来初始化struct?
Matrix2x2 m1 = {1, 2, 3, 4};
Matrix2x2 res(5*m1);
Run Code Online (Sandbox Code Playgroud)
这里,例如,第一个结构通过使用花括号和等号来初始化,而第二个结构是通过从乘法结果中复制值来理解初始化.
我想m1以某种方式在括号的帮助下进行初始化.可能吗?
#pragma once
#include <iostream>
struct Matrix2x2
{
double _00, _01,
_10, _11;
};
std::istream& operator>>(std::istream&, Matrix2x2&);
std::ostream& operator<<(std::ostream&, Matrix2x2&);
Matrix2x2 operator*(const double&, const Matrix2x2&);
#include "Matrix.h"
std::istream& operator>>(std::istream& is, Matrix2x2& m)
{
return is >> m._00 >> m._01 >> m._10 >> m._11;
}
std::ostream& operator<<(std::ostream& os, Matrix2x2& m)
{
return os << m._00 << ' ' << m._01 << std::endl
<< m._10 << ' ' << m._11 << std::endl;
}
Matrix2x2 operator*(const double& c, const Matrix2x2& m)
{
Matrix2x2 res = {c*m._00, c*m._01, c*m._10, c*m._11};
return res;
}
Run Code Online (Sandbox Code Playgroud)
您可以为结构提供用户定义的构造函数:
#include <iostream>
struct Matrix2x2 {
int x1;
int x2;
int x3;
int x4;
Matrix2x2(int a, int b, int c, int d)
: x1(a), x2(b), x3(c), x4(d)
{}
};
int main() {
Matrix2x2 m1 = { 1, 2, 3, 4 }; // list initialization
Matrix2x2 res(1, 2, 3, 4); // calls user-defined constructor
}
Run Code Online (Sandbox Code Playgroud)
并在创建对象时传递参数(用括号括起来).但你应该更喜欢支撑初始化器,因为它不受最令人烦恼的解析:
Matrix2x2 res{ 1, 2, 3, 4 }; // calls user-defined constructor, braced initialization
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
303 次 |
| 最近记录: |