如何声明结构体?
How can I declare a struct?
我目前正在学习c++,并试图理解结构体的用法。
在c++。据我所知,如果你想在main()函数之后定义一个函数,你必须事先声明,就像在这个函数中一样(如果我错了请告诉我):
#include "stdafx.h"
#include <iostream>
#include <string>
void printText(std::string); // <-- DECLARATION
int main()
{
std::string text = "This text gets printed.";
printText(text);
}
void printText(std::string text)
{
std::cout << text << std::endl;
}
我现在的问题是,如果有一种方法来做同样的结构。我不希望总是在main()函数之前定义一个结构体,只是因为我喜欢这样。然而,当我尝试这样做时,我得到了一个错误:
//THIS program DOESN'T work.
#include "stdafx.h"
#include <iostream>
#include <string>
struct Products {std::string}; // <-- MY declaration which DOESN'T work
int main()
{
Products products;
products.product = "Apple";
std::cout << products.product << std::endl;
}
struct Products
{
std::string product;
};
当我删除声明并在主函数之前定义结构体时,程序正常工作,因此我认为我的声明是错误的:
//THIS program DOES work
#include "stdafx.h"
#include <iostream>
#include <string>
struct Products
{
std::string product;
};
int main()
{
Products products;
products.product = "Apple";
std::cout << products.product << std::endl;
}
谁能告诉我,如果有某种方式来声明这样的结构?如果我在代码中有任何重大错误,请原谅我,我只是一个初学者。提前感谢!
在c++中可以预声明(前声明)一个类类型。
struct Products;
然而,以这种方式声明的类类型是不完整的。不完整类型只能在一些非常有限的情况下使用。你可以声明这种类型的指针或引用,也可以在非定义的函数声明中提到它,但是你不能定义这种不完整类型的对象,也不能访问它们的成员。
如果你想定义类Products
的对象或访问类Products
的成员,你别无选择,只能在使用类之前完全定义。
在您的例子中,您在main
中定义了Products
类型的对象,并在那里访问了Products
类的成员。这意味着您必须在main
之前完全定义Products
。
在你的特殊情况下,前向声明没有帮助,因为前向声明只允许你使用指针或引用,例如
struct foo;
foo* bar(foo f*) { return f;}
struct foo { int x; }
然而,struct Products {std::string};
不是一个声明,但是如果你想要一个格式错误的声明和定义。正确的前向声明应该是:
struct Products;
相关文章:
- 卷曲bracers内部结构的声明
- 根据用户回答声明"Players"。用户选择玩家数量。播放器是结构体
- 结构体 S { int align; } 之间的区别;(struct 关键字后的名称)和 struct { int al
- 访问在 C++ 结构中声明的枚举变量
- 当我想为结构体声明新成员时,有些麻烦我不明白
- 如何声明在不同命名空间中定义的结构体
- 在c++头文件中声明结构体
- 在for循环初始化语句中声明未命名结构体
- 如何声明具有other类型成员的两个结构体
- 如何声明结构体?
- 结构体上未加声明的标识符
- c++中声明结构体的问题
- 为什么在链表中声明指向同一结构体的指针?
- 在结构体声明中,空大括号是什么意思?
- 内联结构体声明的Sizeof
- 如何在动态二维数组中存储数据,在结构体中声明,该结构体也被c++中的另一个结构体使用
- 了解隐式声明的默认协结构体
- 为什么编译器不能像变量声明那样在结构体成员中设置 char[] = { .. } 的大小?
- 如何在特定地址声明结构体
- 引用模板类中声明的结构体