c++类的定义不能在main函数内部吗

如题所述

c++支持在函数内部定义类,不过有些限制
1,方法实现只能就地完成,不能分开,因为函数内部不能定义函数,而函数外部看不见这个类定义。
2,不能使用模版。
温馨提示:内容为网友见解,仅供参考
第1个回答  2017-01-16
可以,加一层括号。例子如下:
#include<iostream>
#include<iomanip>
using namespace std;
#include<stdio.h>
main()
{
int num;
{
class Owner
{
private: char name[20]; int mobile;
public:
Owner(char *n, long int m)
{ strcpy(name,n); mobile = m; };
char* getName(){ return name; };
long int getMobile(){return mobile; };
}; // end class
class Owner XX("John",12345);
num = XX.getMobile();
}
printf("num=%d\n",num);
return 0;
}
输出:
num=12345
第2个回答  2017-01-16
写段代码试试就知道了

~~~~~~~~~~~

答案是肯定的

~~
相似回答