c++ - 使用圆括号而不是大括号和等号初始化结构

标签 c++ parentheses curly-braces

如何使用圆括号而不是大括号和等号来初始化结构?

Matrix2x2 m1 = {1, 2, 3, 4};
Matrix2x2 res(5*m1);

例如,在这里,第一个结构是使用大括号和等号初始化的,而第二个结构是通过从乘法结果复制值来初始化的。

我希望 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;
}

最佳答案

你可以为你的结构有一个用户定义的构造函数:

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

并在创建对象时传入参数(括号括起来)。但是你应该更喜欢大括号初始化器,因为它不受 most vexing parse 的影响。 :

Matrix2x2 res{ 1, 2, 3, 4 }; // calls user-defined constructor, braced initialization

关于c++ - 使用圆括号而不是大括号和等号初始化结构,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47581828/

相关文章:

c++ - C++中原子变量的线程安全初始化

Eclipse 代码样式格式化程序 : How to keep closing braces of initializer list in seperate line?

c++ - 停止 directshow 源过滤器时 Flash 崩溃

c++ - 如何用整数 "fmod()"函数替换 "mod()"

c++ - 一个关于派生标准异常类的问题

perl - 在Perl中使用无括号的子例程调用的原因是什么?

java - 正则表达式删除嵌套括号

java - 此行有多个标记 - 标记 ")"上的语法错误,;预期 - token "("上的语法错误,{预期

if-statement - 使用不带花括号的 if 语句是一种不好的做法吗?

c++ - 在我的程序主函数中输入结束时预期为 '}'