[英]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>
。
有兩種方法可以解決這個問題:
smallDude
構造函數以接受int
輸入,如@rturrado 的回答所示:struct smallDude
{
int int1;
int int2;
// constructor
smallDude(int x, int y) : int1{x}, int2{y} {}
};
smallDude
構造函數(從而使smallDude
成為聚合),並直接在其聲明中為成員分配默認值,例如:struct smallDude
{
int int1 = 70;
int int2 = 60;
};
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.