如何声明结构体?

How can I declare a struct?

本文关键字:结构体 声明 何声明      更新时间:2023-10-16

我目前正在学习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;