class CBase
{
int a;
char *p;
};
那麼運行cout<<"sizeof(CBase)="<<sizeof(CBase)<<endl;以後輸出什麼?ios
這個應該很簡單,兩個成員變量所佔的大小——8。c++
第一步:空類git
class CBase
{
};
運行cout<<"sizeof(CBase)="<<sizeof(CBase)<<endl;面試
sizeof(CBase)=1;算法
深度探索c++對象模型中是這樣說的: 那是被編譯器插進去的一個char ,使得這個class的不一樣實體(object)在內存中配置獨一無二的地址。 也就是說這個char是用來標識類的不一樣對象的。 數組
第二步:函數
仍是最初的那個類,運行結果:sizeof(CBase)=8this
第三步:添個虛函數spa
class CBase
{
public:
CBase(void);
virtual ~CBase(void);
private:
int a;
char *p;
};
再運行:sizeof(CBase)=12.net
C++ 類中有虛函數的時候有一個指向虛函數的指針(vptr),在32位系統分配指針大小爲4字節」。那麼繼承類呢?
第四步:
基類就是上面的了不寫了
class CChild :
public CBase
{
public:
CChild(void);
~CChild(void);
private:
int b;
};
運行:cout<<"sizeof(CChild)="<<sizeof(CChild)<<endl;
輸出:sizeof(CChild)=16;
可見子類的大小是自己成員變量的大小加上子類的大小。
面試問題3.(1)對象只容許在堆上建立,(2)對象只容許在棧上建立;
答案:
class HeapOnly
{
public:
HeapOnly()
{
cout<<"constructor. "<<endl;
}
void destroy()
{
delete this;
}
private:
~HeapOnly(){}
};
int main()
{
HeapOnly *p = new HeapOnly;
p->destroy();
HeapOnly h;
h.Output();
return 0;
}
#include <iostream>
using namespace std;
class StackOnly
{
public:
StackOnly()
{
cout<<"constructor." <<endl;
}
~StackOnly()
{
cout<<"destructor." <<endl;
}
private:
void *operator new (size_t);
};
int main()
{
StackOnly s; //okay
StackOnly *p = new StackOnly; //wrong
return 0;
}
本文來自CSDN博客,轉載請標明出處:http://blog.csdn.net/zhangxinrun/archive/2010/12/03/6052551.aspx
面試問題4.在一個不知道升序仍是降序的數據組中查找一個給定的數,
我的想法:1.根據數組的首尾比較,判斷數組的序列形式;2.折半查找算法。
答案:
#include <stdio.h>
#include <assert.h>
using namespace std;
static bool flag = true;
bool intCompare(int value1, int value2)
{
return (value1 > value2) == flag;
}
int binary_search_i(int a[], int value, int start, int end)
{
if (start > end) return -1;
int pos = (start + end)/ 2;
if (value == a[pos])
{
return pos;
}
else if (intCompare(value, a[pos]))
{
return binary_search_i(a, value, pos + 1, end);
}
else
{
return binary_search_i(a, value, start, pos - 1);
}
}
int binary_search(int a[], int value, int n)
{
assert((a != NULL) && (n > 0));
if ((n == 1) || (a[0] == a[n - 1]))
{
if (a[0] == value)
{
return 0;
}
else
{
return -1;
}
}
if (a[0] < a[n - 1])
{
flag = true;
}
else
{
flag = false;
}
int temp = binary_search_i(a, value, 0, n - 1);
while ((temp > 0) && (a[temp] == a[temp - 1]))
{
--temp;
}
return temp;
}
int main()
{
//int a[] = {1, 3, 5, 7, 7, 7, 7, 7, 7, 7, 9, 10, 11};
int a[] = {11, 10, 9, 7, 7, 7, 7, 7, 5, 3, 1};
int arrayNum = sizeof(a) / sizeof(int);
for(int i = 0; i < arrayNum; ++i)
{
printf("a[%d]=%d/t", i, a[i]);
}
printf("/n");
int value = 0;
while(1)
{
printf("Input search value:");
scanf("%d", &value);
printf("Pos in array:%d/n", binary_search(a, value, arrayNum));
}
return 0;
}
面試問題5.那些算法是穩定排序,那些算法是不穩定排序。
答案:上網上搜索一下。