小编El3*_*0st的帖子

我怎样才能声明一个结构?

我目前正在学习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;
}
Run Code Online (Sandbox Code Playgroud)

我现在的问题是,是否有办法对结构进行相同的处理.我不想总是在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;
};
Run Code Online (Sandbox Code Playgroud)

当我删除decleration而不是在main函数之前 …

c++ struct declaration

0
推荐指数
1
解决办法
93
查看次数

标签 统计

c++ ×1

declaration ×1

struct ×1