![](/img/trans.png)
[英]How do I initialise a const array struct field with the output of a function?
[英]How do I create and initialise a simple struct without providing a constructor?
假設我有這種類型:
struct T
{
SomeType a;
OtherType b;
};
我認為有某種方法可以聲明T
類型的對象並定義a
和b
的初始化值,但是我不記得它是如何工作的,甚至不知道它叫什么,所以我可以查找它。 T t(a, b)
之類的SomeType
,其中a
和b
分別是SomeType
和OtherType
類型。
我如何在不聲明構造函數的情況下實現這一目標,這叫什么?
您可以寫成T t = {a, b}
。 不過,這僅適用於POD 聚合 (當然也適用於適當的構造函數)。
您已使用c ++ 11進行了標記,因此只需執行以下操作:
#include <iostream>
struct T
{
int a;
float b;
};
int main()
{
T t{1,2.2};
std::cout << t.a << ":" << t.b << std::endl;
}
C ++ 11用“ {}”代替統一的初始化列表,這意味着您可以初始化。 類,以“ {}”作為結構之前,可以像這樣初始化結構
T t{someTypeA, otherTypeB};// someTypeA and someTypeB must be defined
這是一個簡單的測試代碼
#include <iostream>
using namespace std;
class B
{
public:
int a;
};
class C
{
public:
int a;
};
struct A
{
B b;
C c;
};
int main(int argc, char** argv)
{
B b;
C c;
b.a = 1;
c.a = 2;
A a{b, c};
cout << a.b.a << a.c.a << endl;
return 0;
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.