1、用sizeof求出所有基本数据类型的长度
#include
#include
using namespace std;
int main()
{
int a, b, c, d, e, f, g, h,i,j,k;
a=sizeof(char);
b = sizeof(short);
c = sizeof(int);
d = sizeof(long);
e= sizeof(unsigned int);
f = sizeof(long long);
g = sizeof(float);
h = sizeof(double);
cout << "char:" << a;
cout << "字节\nshort:" << b << "字节\nint:" << c << "字节\nlong:" << d << "字节\nunsigned int:" << e << "字节\nlong long:" << f;
cout << "字节\nfloat:" << g << "字节\ndouble:" << h <<"字节"<< endl;
system("pause");
return 0;
}
或者
#include
using namespace std;
class DataType
{
private:
enum TYPE { CHAR, INT, FLOAT };
union DATA
{
int i;
char c;
float f;
};
TYPE type;
DATA data;
public:
DataType(char c)
{
data.c = c;
type = CHAR;
}
DataType(int i)
{
data.i = i;
type = INT;
}
DataType(float f)
{
data.f = f;
type = FLOAT;
}
void show()
{
switch (type)
{
case CHAR:
cout << data.c << endl;
break;
case INT:
cout << data.i << endl;
break;
case FLOAT:
cout << data.f << endl;
break;
default:
break;
}
}
};
int main()
{
DataType d(‘a’);
d.show();
DataType dd(123);
dd.show();
DataType ddd(123.2f);
ddd.show();
return 0;
}
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)