我们可以在C+;中的main函数之后定义结构吗+;? 我们可以在C++中的主程序之后定义结构吗?当我们定义函数时,我们可以在主程序之前声明函数,然后在主函数之后编写函数定义。我想知道,在定义结构时,我们是否可以做类似的事情。谢谢。

我们可以在C+;中的main函数之后定义结构吗+;? 我们可以在C++中的主程序之后定义结构吗?当我们定义函数时,我们可以在主程序之前声明函数,然后在主函数之后编写函数定义。我想知道,在定义结构时,我们是否可以做类似的事情。谢谢。,c++,struct,C++,Struct,编辑:正如评论中提到的@user207933,我错误地使用了术语“转发声明”。我相应地更新了我的答案 如果只想存储指向该结构的指针,则可以转发声明结构。但是,一旦定义了结构,就只能调用该指针上的方法 #include <iostream> // forward declaration of struct struct S; // pointer can be defined after forward declaration S * s; void workOnSPointer(

编辑:正如评论中提到的@user207933,我错误地使用了术语“转发声明”。我相应地更新了我的答案

如果只想存储指向该结构的指针,则可以转发声明结构。但是,一旦定义了结构,就只能调用该指针上的方法

#include <iostream>

// forward declaration of struct
struct S;
// pointer can be defined after forward declaration
S * s;

void workOnSPointer();

int main()
{
    workOnSPointer();
}

// definition of struct
struct S
{
    S() : bar(42) {}
    void foo() { std::cout << "bar is " << bar << "\n"; }
    int bar;
};

// methods can only be called after definition
void workOnSPointer()
{
    S * s = new S();
    s->foo();
    delete s;
}
文件
S.cpp

#include "S.h"
#include <iostream>

S::S() : bar(42) {}
void S::foo() { std::cout << "bar is " << bar << "\n"; }
#include "S.h"

int main()
{
    S s;
    s.foo();
}
如果编译
S.cpp
main.cpp
,然后链接生成的对象文件,您将获得与开始时代码相同的行为

我们可以在C++中的主程序之后定义结构吗? 我想你指的是

main
函数。是的,我们可以在
main
函数之后定义类(包括结构)。演示:

int main(){}
struct S{};
当我们定义函数时,我们可以在主程序之前声明函数,然后在主程序之后编写函数定义。我想知道,在定义结构时,我们是否可以做类似的事情

同样适用于类,您可以(转发)在函数之前声明它们,并在函数之后定义它们。但是,不完整(声明但未定义)类的使用非常有限。您可以定义指向它们的指针和引用,但不能创建它们,也不能调用任何成员函数。演示:

struct S;     // (forward) declaration of a class
S* factory(); // (forward) declaration of a function
int main(){
    S* s = factory(); // OK, no definition required
    // s->foo();      // not OK, S is incomplete
    // S s2;          // not OK
}
struct S{             // definition of a class
    void foo();       // declaration of a member function
};
S* factory() {
     static S s;      // OK, S is complete
     s.foo();         // OK, note how the member function can be called
                      // before it is defined, just like free functions
     return &s;
}
void S::foo() {}      // definition of a member function

你为什么不试试呢?是的,你能做到。查找前向声明。当你说“主程序”时,你的意思是“主函数”结构和类定义通常进入headers@user2079303是正确的,向前声明可用于定义指针。另一个具有向前声明的
struct
void main()
的示例不正确,应该是
int main()
int main(){}
struct S{};
struct S;     // (forward) declaration of a class
S* factory(); // (forward) declaration of a function
int main(){
    S* s = factory(); // OK, no definition required
    // s->foo();      // not OK, S is incomplete
    // S s2;          // not OK
}
struct S{             // definition of a class
    void foo();       // declaration of a member function
};
S* factory() {
     static S s;      // OK, S is complete
     s.foo();         // OK, note how the member function can be called
                      // before it is defined, just like free functions
     return &s;
}
void S::foo() {}      // definition of a member function