(C/C++) 结构体初始化语法
当我创建自己的结构时,说:
struct myStruct{
int data1;
int data2;
string data3;
}
我可以像这样初始化 myStruct 类型的实例:
myStruct instance1;
所以我的问题是,为什么我经常看到在结构初始化期间写入“struct”? 也许这是一个不准确的说法,所以这里是我的意思的一个例子:
/*This is a tiny program that checks
to see if a file exists in
the current working directory. */
#include <sys/stat.h>
#include <iostream>
using namespace std;
const string FILENAME = data.txt;
int main(){
struct stat fileStatus; //<-- HERE HERE HERE!
if (FileExists(FILENAME, fileStatus)){
cout << "File Does Exist" << endl;
}else{
cout << "File Does NOT Exist" << endl;
}
return 0;
}
bool FileExists(const string & fileName,struct stat & fileStatus){
bool fileDoesNotExist = stat (fileName.c_str(), &fileStatus);
return !fileDoesNotExist;
}
> 第 13 行:struct stat fileStatus;
这是出于某种原因用 C 语言完成的吗?
带有宏或 typedef 的东西?
我只是不明白为什么会这样。
When I make my own struct, say:
struct myStruct{
int data1;
int data2;
string data3;
}
I can initialize an instance of type myStruct like this:
myStruct instance1;
So my question is, why am I often seeing "struct" written during the initialization of a struct?
Maybe that's an inaccurate statement so here is an example of what I mean:
/*This is a tiny program that checks
to see if a file exists in
the current working directory. */
#include <sys/stat.h>
#include <iostream>
using namespace std;
const string FILENAME = data.txt;
int main(){
struct stat fileStatus; //<-- HERE HERE HERE!
if (FileExists(FILENAME, fileStatus)){
cout << "File Does Exist" << endl;
}else{
cout << "File Does NOT Exist" << endl;
}
return 0;
}
bool FileExists(const string & fileName,struct stat & fileStatus){
bool fileDoesNotExist = stat (fileName.c_str(), &fileStatus);
return !fileDoesNotExist;
}
>
LINE 13: struct stat fileStatus;
Is this something that was done in C for some reason?
Something with a macro or a typedef?
I just don't understand why this is the way it is.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
这是一个 C 的事情;没有充分的理由继续在 C++ 中这样做。1
在 C 中,
struct
是类型名的一部分,例如:定义一个名为
struct foo.在 C++ 中,它定义了一个名为
foo
的类型。在 C 中,您通常可以将这种烦恼隐藏在 typedef 后面:1 At least, not in code that couldn't possibly also be compiled as C (such as the example in your question).
This is a C thing; there's no good reason to continue to do it in C++.1
In C,
struct
is part of the typename, e.g.:defines a type called
struct foo
. In C++, it defines a type calledfoo
. In C, you can usually hide this irritation behind a typedef:1 At least, not in code that couldn't possibly also be compiled as C (such as the example in your question).
您可以通过像这样调用它来完成您想要的操作:
因此,每当您创建 mystruct 项时,它都会创建一个指向您的结构的指针,否则您必须通过
struct mystruct *object; 调用您的结构。
You can do what you want by instead calling it like this:
So that's whenever you make a mystruct item it creates a pointer to your struct, else you have to call your struct by
struct mystruct *object;