簡體   English   中英

如何聲明結構?

[英]How can I declare a struct?

我目前正在學習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;
};

當我刪除declecle並在main函數之前定義結構時,該程序可以正常工作,因此我認為declecle在某種程度上是錯誤的:

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM