2013-03-19 63 views
1

我在我的程序中使用了以下结构。C++发生结构错误,为什么不允许这样做?

struct terminator{ 
    int id; 
    string type; 
    union{ 
     terminator *next; 
     int empty; 
    }; 
}; 

在主,我有以下代码:

int main(){ 
    terminator root = {0, "", NULL}; 
    root = {0, "", NULL}; //NOT ALLOWED WHY? Trying to set to its original value. 
} 

这提供了以下错误信息:

g++ lab8.cc -std=c++11 
lab8.cc: In function 'int main()': 
lab8.cc:78:21: error: no match for 'operator=' in 'root = {0, "", 0}' 
lab8.cc:78:21: note: candidates are: 
lab8.cc:6:8: note: terminator& terminator::operator=(const terminator&) 
lab8.cc:6:8: note: no known conversion for argument 1 from '<brace-enclosed in 
itializer list>' to 'const terminator&' 
lab8.cc:6:8: note: terminator& terminator::operator=(terminator&&) 
lab8.cc:6:8: note: no known conversion for argument 1 from '<brace-enclosed in 
itializer list>' to 'terminator&&' 

但是,这是确定的,而不是:

int main(){ 
    terminator root = {0, "", NULL}; 
    root = *(new terminator); 
    root.id=0; 
    root.type=""; 
    root.next=NULL; 
} 

为什么这是吗?任何方式来解决它?

回答

3

在第一种情况下,你是初始化结构。

在第二种情况下,您正在尝试赋值给已声明的变量,除非您的编译器支持将复合文字作为扩展名,否则不起作用。 (即使是这样,你需要写

root = (terminator){ 0, "", NULL }; 

实际上使它工作。)

如果你可以使用C++ 11(这好像你这样做),你也可以采取所谓的“初始化列表”的新功能的优势,其运动类似的语法:

root = terminator{ 0, "", NULL }; 
+1

与该问题没有直接关系,但在C++ 11中,'NULL'的使用已被弃用,以支持'nullptr'。 – Gorpik 2013-03-19 09:09:39

+0

@Gorpik这很有趣。谢谢(你的)信息! – 2013-03-19 09:10:10

2

你需要告诉编译器的RHS是terminator类型:

root = terminator{0, "", NULL}; 
+0

。 – ecatmur 2013-03-19 09:04:31

+0

哦,我明白了。没有注意到'-std = C++ 11'标志。我的错。 – 2013-03-19 09:05:12

1

线terminator root = {0, "", NULL};做集合初始化,这是允许在没有一个构造函数的构造形式。 =这并不意味着分配。在C++ 11可以使用支架语法构建terminator类型的匿名临时对象,然后可以将分配给root:@ H2CO3 OP是使用C++编译器11

root = terminator{0, "", nullptr};