C++实例化结构错误,为什么不允许这样做?
C++ instansing a struct error, why isn't this allowed?
我在程序中使用以下结构体:
struct terminator{
int id;
string type;
union{
terminator *next;
int empty;
};
};
main中有以下代码:
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;
}
为什么会这样?有办法绕过它吗?
在第一种情况下,您正在初始化结构。
在第二种情况下,您试图将赋值给已经声明的变量,除非您的编译器支持复合文字作为扩展,否则这将不起作用。(即使是这样,你也需要写root = (terminator){ 0, "", NULL };
让它实际工作。)
如果你可以使用c++ 11(看起来你是这样做的),你还可以利用名为"初始化列表"的新特性,它的语法类似:
root = terminator{ 0, "", NULL };
你需要告诉编译器RHS的类型是terminator
:
root = terminator{0, "", NULL};
terminator root = {0, "", NULL};
行聚合初始化,这是在没有构造函数时允许的一种构造形式。这里的=
并不意味着赋值。在c++ 11中,您可以使用大括号语法来构造terminator
类型的匿名临时对象,然后您可以将其分配给root
:
root = terminator{0, "", nullptr};
相关文章:
- 为什么C++的文件 I/O 在读取文本文件时忽略初始空行?我怎样才能让它不这样做?
- 函数如何在不这样做的情况下在新线程上运行"as if"?
- 为什么在接受输入后循环退出时不会这样做
- 为什么我不能在未链接的 DLL 上调用方法,但可以这样做?C++
- 为什么指针不能指向张贴增量,而可以这样做才能预先递增
- 为什么循环结束时不这样做?
- 从用户应用程序访问环0模式(以及Borland允许这样做的原因)
- 为什么static_cast不允许这样做
- 错误:不允许指向不完整类类型的指针.我该怎么做
- 为什么编译器允许这样做
- 通过单行中的XOR交换整数.在c++11中真的允许这样做吗
- 声明和带有定义的声明.为什么不允许这样做
- 将char * *变量赋值给char * const *变量——为什么允许这样做?
- strlen to int 为什么我不能这样做?
- 在类中传递私有变量——为什么不允许这样做
- 为什么在使用constexpr时允许这样做?
- C++实例化结构错误,为什么不允许这样做?
- 共享库没有链接/不能这样做
- 1D 数组衰减为指针,但 2D 数组不会这样做,为什么?
- 为什么允许这样做