简体   繁体   English

C++ 结构初始化断言失败

[英]C++ struct initialization assertion fails

#include <cassert>
#include <string>
struct AStruct 
{ 
    int x; 
    char* y; 
    int z; 
};
int main()
{ 
    AStruct structu = {4, "Hello World"};
    assert(structu.z == ???);
}

What should I write in place of ???我应该写什么来代替??? to have a successful assertion?有一个成功的断言?
I used assert(structu.z == 0);我用assert(structu.z == 0); but unfortunately got the error但不幸的是得到了错误
int main(): Assertion 'structu.z == 0 failed.Aborted'

You want:你要:

 assert(structu.z == 0);

Your code assigns to the z member instead of testing it.您的代码分配给 z 成员而不是对其进行测试。 And if you did get the message your edited question says you did, your compiler is broken.如果您确实收到了您编辑的问题所说的消息,那么您的编译器就坏了。 Which one is it?哪一个?

By "successful", I'm assuming you mean one that doesn't create an error message.通过“成功”,我假设您的意思是不会创建错误消息的。 You probably want:你可能想要:

assert(structu.z == 0);

Note that I'm using == , and not = .请注意,我使用的是== ,而不是=

This assertion should never trigger, because with the code given, structu.z is guaranteed to be equal to 0 .这个断言不应该触发,因为给出的代码, structu.z保证等于0

assert(structu.z == 0) should work because the member z would be value initialized. assert(structu.z == 0)应该可以工作,因为成员z将被初始化。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM