嵌套结构并使用构造函数作为默认值但转换错误

Nested Structures and using constructor for default value but conversion error

出于某种原因,当我使用构造函数为嵌套结构设置一些默认值时,出现以下错误。但似乎代码应该可以工作。谁能告诉我哪里错了?

#include <stdio.h>
#include <string.h>
#include <iostream>

using namespace std;

struct smallDude
{
    int int1;
    int int2;

    // Default constructor
    smallDude()
    {
        int1 = 70;
        int2 = 60;
    }
};

struct bigDude 
{
    // structure within structure
    struct smallDude second;
}first;

int main() 
{
    bigDude first = {{2, 3}};
    cout<< first.second.int1<<endl;
    cout<< first.second.int2;
    return 0;
}

错误输出:

main.cpp:28:28: error: could not convert ‘{2, 3}’ from ‘’ to ‘smallDude’
   28 |     bigDude first = {{2, 3}};
      |                            ^
      |                            |
      |                            

您缺少接收两个 int 值的 smallDude 构造函数:

smallDude(int x, int y) : int1{x}, int2{y} {}

Demo

smallDude 有一个用户声明的默认构造函数,因此它不是聚合类型,因此不能像您尝试的那样从 <brace-init-list> 初始化。

有两种方法可以解决这个问题:

  1. 更改 smallDude 构造函数以接受 int 输入,例如 显示:
struct smallDude
{
    int int1;
    int int2;

    // constructor
    smallDude(int x, int y) : int1{x}, int2{y} {}
};

Online Demo

  1. 完全摆脱所有 smallDude 构造函数(从而使 smallDude 成为聚合)并直接在成员的声明中为其分配默认值,例如:
struct smallDude
{
    int int1 = 70;
    int int2 = 60;
};

Online Demo