繁体   English   中英

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

[英]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() 
{
    first = {{2, 3}};
    cout<< first.second.int1<<endl;
    cout<< first.second.int2;
    return 0;
}

错误 Output:

main.cpp:29:31: error: could not convert ‘{3, 6}’ from ‘’ to ‘smallDude’
29 |     bigDude first = {1, {3, 6}};
   |                               ^
   |                               |
   |                               <brace-enclosed initializer list>

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

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

  1. 更改smallDude构造函数以接受int输入,如@rturrado 的回答所示:
struct smallDude
{
    int int1;
    int int2;

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

在线演示

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

在线演示

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

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

演示

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM