如何声明结构?

时间:2016-10-05 18:55:03

标签: c++ struct declaration

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

当我删除decleration而不是在主函数之前定义结构时,该程序正常工作,所以我假设我在某种程度上错误地解决了这个问题:

//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;
}

有人能告诉我是否有某种方式来声明这样的结构?如果我在代码中有任何重大错误,请耐心等待,我只是一个初学者。 提前谢谢!

2 个答案:

答案 0 :(得分:11)

您可以在C ++中预先声明(转发声明)类类型。

struct Products;

但是,以这种方式声明的类类型不完整。不完整类型只能以非常有限的方式使用。您将能够声明指向此类型的指针或引用,您可以在非定义函数声明等中提及它,但您将无法定义此类不完整类型的对象或访问其成员。

如果要定义类Products的对象或访问类Products的成员,除了在使用之前完全定义类之外别无选择。< / p>

在您的情况下,您要在Products中定义main类型的对象,并在那里访问类Products的成员。这意味着您必须在Products之前完全定义main

答案 1 :(得分:1)

在您的特定情况下,前向声明不会有帮助,因为前向声明仅允许您使用指针或引用,例如在

struct foo;
foo* bar(foo f*) { return f;}
struct foo { int x; }

然而,

struct Products {std::string};

不是声明,但如果你想要一个格式错误的声明和定义。 正确的前瞻性声明是:

struct Products;