c++中,函数体中能否定义结构体和类?

2025-03-04 06:05:57
推荐回答(2个)
回答1:

不能
只能在函数外定义的
否则会被编译报错
其实你可以直接写一个简单的函数
里面就有结构体或类的定义
运行一下
你就可以知道了

回答2:

可以,简单写一个


void test()

{

struct MyStruct

{

private:

int z;

public:

int x;

int y;

void init()

{

x = 0;

y = 0;

}

};

class MyClass

{

public:

MyClass()

{

OutputDebugString("MyClass");

printf("MyClass");

}

~MyClass()

{

OutputDebugString("~~~MyClass");

printf("~~~MyClass");

}


private:


};



MyStruct st;

st.init();


MyClass cl;

}


vs可以编译和正常运行