【问题标题】:How can I declare a struct?如何声明一个结构?
【发布时间】:2016-10-05 18:55:03
【问题描述】:

我目前正在学习 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 并在 main 函数之前定义结构 before 时,程序可以运行,所以我认为 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;
}

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

【问题讨论】:

  • struct Name; 是您正在寻找的前向声明。
  • 您应该将确切的错误消息与问题一起发布
  • 这怎么跑题了?
  • 前向声明在这里不起作用,因为 main() 使用结构中的成员。您必须在 main 之前定义结构。如果您不喜欢美学,请将结构放在标题中。

标签: c++ struct declaration


【解决方案1】:

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

struct Products;

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

如果你想定义Products类的对象或访问Products类的成员,你别无选择,只能在使用之前完全定义类。

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

【讨论】:

  • @AnT "你必须完全定义"我认为声明就足够了。
  • @πάνταῥεῖ:我不确定你的意思。 OP 的用法要求类 definitionmain 可见(即需要定义声明,而不是非定义声明)。
  • @AnT 关于声明定义的混淆。前向声明不是完整的类声明
  • @πάνταῥεῖ 恕我直言,您似乎是对公认术语感到困惑的人。
  • @TimSeguine 请放心,我不是。
【解决方案2】:

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

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

然而,

struct Products {std::string};

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

struct Products;

【讨论】:

  • 说实话,我没有仔细阅读,但我也没有投反对票。我建议切换答案的第一部分和第二部分,因为第一部分与给定问题无关。
  • @Andrey 好点。实际上我只是后来才添加了最后一句话。据我了解,它是关于向前声明一个结构的问题,而 OPs 代码只是作为一个例子
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2013-06-23
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-10-23
  • 2017-01-30
  • 1970-01-01
相关资源
最近更新 更多