【发布时间】: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