65,187
社区成员




//program 12.7.1.cpp const成员和引用成员
#include <iostream>
using namespace std;
int f;
class CDemo {
private :
const int num; //常量型成员变量
int & ref; //引用型成员变量
int value;
public:
CDemo( int n):num(n),ref(f),value(4)
{
}
};
int main(){
int*p;
cout << sizeof(CDemo) << endl;
cout << sizeof(int) << endl;
cout << sizeof(p) << endl;
system("pause");
return 0;
}
//program 12.7.1.cpp const成员和引用成员
#include <iostream>
using namespace std;
char f;
class CDemo
{
private:
const char num; //常量型成员变量
char ref; //引用型成员变量
char value;
public:
CDemo(int n) : num(n), ref(f), value(4)
{
}
};
int main()
{
char *p;
cout << sizeof(CDemo) << endl;
cout << sizeof(int) << endl;
cout << sizeof(char) << endl;
cout << sizeof(char&) << endl;
cout << sizeof(p) << endl;
system("pause");
return 0;
}
其结果是:
3
4
1
1
8//program 12.7.1.cpp const成员和引用成员
#include <iostream>
using namespace std;
char f;
class CDemo
{
private:
const char num; //常量型成员变量
char &ref; //引用型成员变量
char value;
public:
CDemo(int n) : num(n), ref(f), value(4)
{
}
};
int main()
{
char *p;
cout << sizeof(CDemo) << endl;
cout << sizeof(int) << endl;
cout << sizeof(char) << endl;
cout << sizeof(p) << endl;
system("pause");
return 0;
}
测试过turbo C++,mingw64,mingw,MS VC6.0和2010,发现默认都是按是指针长度对齐的。在64位下面程序输出是:
24
4
1
8
#include <stddef.h>
#include <stdio.h>
struct s1 {
char c;
int n;
};
struct s2 {
char c;
void *p;
};
int
main(int argc, char *argv[])
{
printf("%d\n", (int)offsetof(struct s1, c));
printf("%d\n", (int)offsetof(struct s1, n));
printf("%d\n", (int)offsetof(struct s2, c));
printf("%d\n", (int)offsetof(struct s2, p));
return 0;
}
#include <iostream>
struct A
{
const long double a;
};
struct B:virtual A
{
char s;
};
struct C
{
char s;
};
int main()
{
std::cout<<sizeof(A)<<std::endl;
std::cout<<sizeof(std::declval<const void*>())<<std::endl;
std::cout<<sizeof(B)<<std::endl;
std::cout<<sizeof(C)<<std::endl;
return 0;
}
测试连接:
https://gcc.godbolt.org/z/nHfRvX