編輯:
雖然格式錯誤這個問題有一個很好的catch.So,我編輯這在誰碰到這個問題絆倒以後的訪問者更好的格式保留此。向量變更類的大小
在下面的代碼示例可有人請解釋爲什麼不同階級的大小比memcpy
結束後的預計?是什麼原因?
Here是Ideone的在線演示。
#include<iostream>
#include<vector>
#include<cstdio>
#include<cstring>
using namespace std;
class A
{
public:
int a;
virtual void f1() { cout <<"inside a::f1\n"; }
A() { a = 1; }
};
class B
{
public:
int b;
virtual void f2() { cout <<"inside b::f2\n"; }
virtual void f5() { cout <<"inside b::f5\n"; }
B() { b = 2; }
};
class C : public A, public B
{
public:
int c;
void f1() { cout <<"inside c::f1\n"; }
void f2() { cout <<"inside c::f2\n"; }
virtual void f3() { cout <<"inside c::f3\n"; }
virtual void f4() { cout <<"inside c::f4\n"; }
C() { c = 3; }
};
int fun()
{
int a = 1;
return a * 2;
}
int main()
{
C c;
C c2;
int (*g)() = &fun;
void (A::*g1)() = &A::f1;
void (C::*g2)();
g2 = &C::f1;
(c.*g2)();
printf("%p\n",g2);
cout << sizeof(g2) << endl;
g2 = &C::f2;
(c.*g2)();
printf("%p\n", g2);
// Why is the output 1 here in g++ or visual C++?
cout << g2;
// Why is the sizeof returning 8? Please explain.
cout << sizeof(g2) << endl;
g2 = &C::f1;
std::vector<unsigned char> a_vec(sizeof(g2));
memcpy(&a_vec[0], &g2, sizeof(g2));
for(size_t i = 0; i < sizeof(g2); ++i)
{
cout << hex << static_cast<unsigned>(a_vec[i]) << " ";
}
cout << endl;
g2 = &C::f2;
std::vector<unsigned char> a_vec1(sizeof(g2));
memcpy(&a_vec1[0], &g2, sizeof(g2));
for(size_t i = 0; i < sizeof(g2); ++i)
{
cout << hex << static_cast<unsigned>(a_vec1[i]) << " ";
}
cout << endl;
cout << sizeof(g) <<endl;
cout << sizeof(g1) <<endl;
cout << sizeof(g2) <<endl;
// Why is sizeof(C) printing 14 and not 20 in visual C++?
// If yes why is this so ?
cout << sizeof(C) << endl;
cout << sizeof(c2) << endl;
cout << (&c) << endl;
cout << c.a << endl;
cout << c.b << endl;
cout << c.c << endl;
return 0;
}
從上面的代碼示例中,我得到的輸出是:
inside c::f1
0x1
8
inside c::f2
0x5
18
1 0 0 0 0 0 0 0
5 0 0 0 0 0 0 0
4
8
8
14
14
0xbffe375c
1
2
3
以下是我的問題:
爲什麼輸出
1
這裏用g ++或Visual C++?cout < < g2;
爲什麼
sizeof
返回8
?請解釋。COUT < <的sizeof(G2)< < ENDL;
爲什麼
sizeof(C)
打印在Visual C14
,而不是20
++?如果是的話爲什麼這樣呢?COUT < <的sizeof(C)< < ENDL;
請注意,如果memcpy代碼被註釋了,sizeof(C)將打印20,如果它未被註釋,則打印14 ..請解釋 –
並至少提供一個問題... – RvdK
請編輯您的問題,一些文本,解釋問題是什麼,輸出是什麼等等。解析這段長長的代碼來閱讀註釋並不是很好。 – Mat