给要面试的你们存点干货 -_-
--联合体 --考察联合体共用内存
static void testUnion()
{
union MyUnion
{
int a;
char b[2];
}tU;
tU.a = 0;
tU.b[0] = 16; //0x10
tU.b[1] = 1; //0x1
printf("unionVlaue:%d", tU.a);
//-----tU.a 需要初始化 值为0x110 = 272 否则乱码
}
--拷贝-------------------------------------------------------------
static char* testCpy(char* dest, int destSize, const char* src)
{
if (!src)
return nullptr;
char* temp = dest;
while (*src && destSize-- > 1) //预留一位存储 结尾 0
{
*temp++ = *src++;
}
*temp = 0;
return dest;
}
--类调用-------------------------有基先调基,无基调子类,最后调自己,析构反过来
--调用类型1
class grandFather
{
public:
grandFather() { printf("grandFather\n"); };
~grandFather() { printf("~grandFather"); };
private:
};
class father:public grandFather
{
public:
father() { printf("father\n"); };
~father() { printf("~father"); };
private:
};
class chile
{
public:
chile() { printf("chile"); };
~chile() { printf("~chile"); };
private:
father m_father;
};
grandFather
father
chile~chile
~father
~grandFather
--调用类型2
class chile
{
public:
chile() { printf("chile\n"); };
~chile() { printf("~chile\n"); };
private:
};
class father:public grandFather
{
public:
father() { printf("father\n"); };
~father() { printf("~father\n"); };
private:
chile m_chile;
};
grandFather
chile
father
~father
~chile
~grandFather
//--------合并排序 -----考察指针 递归与非递归-----------------------------------------
struct Node
{
int value;
Node *next;
};
//递归合并
Node* Merge(Node *A, Node *B)
{
if (!A)
return B;
if (!B)
return A;
Node *head = nullptr;
if (A->value < B->value) //小的在前
{
head = A;
head->next = Merge(A->next, B);
}
else
{
head = B;
head->next = Merge(B->next, A);
}
return head;
}
//非递归
Node* MergeB(Node *A, Node *B)
{
if (!A)
return B;
if (!B)
return A;
Node *head = nullptr;
Node *current = NULL;
while(A && B)
{
Node *temp = nullptr;
if (A->value < B->value)
{
temp = A;
A = A->next;
}
else
{
temp = B;
B = B->next;
}
if (!head) //头
{
head = temp;
current = temp;
}
else //中
{
current = current->next = temp;
}
}
//末尾
if (A)
current->next = A;
if(B)
current->next = B;
return head;
}
//取中间
Node Mid(const Node *A)
{
if (!A)
return Node();
const Node *temp = A;
while (temp)
{
temp = temp->next;
if (temp)
{
temp = temp->next;
A = A->next;
}
}
return *A;
}
--String重载 -----------考察 operator----------------------------------------
class String {
public:
String(const char* data);
~String();
String &operator = (const String& data);
private:
char* m_buff;
};
String::String(const char* data)
{
this->~String();
int size = strlen(data)+1; //添加一个结束符
m_buff = new char[size]; //知识点---new char() 分配单个字符 new char[] 分配数组
strcpy_s(m_buff, size, data);
}
String::~String()
{
if (m_buff) {
delete m_buff;
}
m_buff = nullptr;
}
String & String::operator=(const String& data)
{
String(data.m_buff);
return *this; //返回地址
}