[英]Can I typedef unnamed struct/class in c++?
在 C 中,我可以 typedef unnamed (no tag) 結構:
typedef struct {
int val;
} Foo_t;
但是當我嘗試在 c++ 中做同樣的事情時:
typedef struct
{
A(int a) : a_var(a) {}
int a_var;
} A;
typedef struct : public A
{
B(int a, int b) : A(a), b_var(b) {}
int b_var;
} B;
B &getB()
{
static B b(1, 2);
return b;
}
int main() {}
output :
error: ISO C++ forbids declaration of ‘A’ with no type
error: only constructors take member initializers
error: class ‘<unnamed struct>’ does not have any field named ‘A’
我知道我正在使用“未命名”結構的構造函數A(int a)
,但在它之后,它是typedef
ed。 所以構造函數只能用於知道類型
例如這個 typedef 聲明的問題
typedef struct
{
A(int a) : a_var(a) {}
int a_var;
} A;
是在未命名的結構中使用未聲明的名稱 A 作為構造函數的名稱。 所以這個聲明是無效的。
順便說一句,C 中也存在同樣的問題。
例如,考慮用於定義鏈表節點的結構的 typedef 聲明。
typedef struct
{
int data;
A *next;
} A;
同樣,結構定義中的名稱A
是未定義的。
即使你會這樣寫
typedef struct A
{
int data;
A *next;
} A;
盡管如此,名稱A
仍未在 C 的結構中聲明。 你必須寫在 C
typedef struct A
{
int data;
struct A *next;
} A;
另一方面,在 C++ 中,這樣的 typedef 聲明是有效的。
是的,你可以,但正如你所說,在結構中使用類型名稱是不可能的。
// this is valid
typedef struct{
int x;
void set(int n){x=n;}
} A;
// this is not
typedef struct{
int x;
B(int n){x = n;}
} B;
// you can only have constructor with named structs
typedef struct st_C{
int x;
st_C(int n){x = n;}
} C;
// this is valid
C *foo = new C(3);
在 C 中,您經常必須像這樣編寫 typdef:
typedef struct {
int val;
} Foo_t;
為了避免不得不寫
struct Foo_t f;
每次,這很快就會變得相當乏味。
在 C++ 中,所有struct
union
s 和enum
s 聲明的行為就像它們是隱式的typedef
一樣。 所以你可以像這樣聲明一個結構:
struct A
{
A(int a) : a_var(a) {}
int a_var;
};
但是,C++ 中的結構通常是聚合(數據的簡單集合),您不需要構造函數。 所以以下是好的:
struct A
{
int a_var;
int b_var;
};
構造函數由編譯器隱式定義,當您使用帶有大括號的值初始化時:
A a{};
結構的所有成員都將被清零。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.