簡體   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