1、函数内的static变量会被初始化几次?说一下它的生命周期和什么时候使用。你经常在什么情况下使用static函数?
-初始化1次,生命周期是整个项目。例如异步加载图片中,统计图片张数。
2、lua的基本数据类型有哪几种?lua如何释放对象内存空间?
-number、string、nil、function、table、thread,user data,boolean
3、请讲述static_cast,dynamic_cast,reinterpreter_cast作用。
-静态类型转换,不安全;
-动态类型转换,安全,如果不成功,返回null
-reinterpreter_cast是强制类型转换
4、class A
{
public:
A():value(0){}
~A(){if (value) delete value}
int* value;
void show()
{
printf(“%d”,*value);
}
};
void fun(A a)
{
a.show();
}
int main()
{
int* value = new int(10);
A a;
a.value = value;
fun(a);
return 0;
}
这段代码的输出结果是什么?是否存在问题?如果有问题原因是什么?
-10 , 有问题 ,默认的拷贝构造是浅拷贝,所以出现二次删除。
5、 void A(char* p)
{
p = new char[100];
}
函数A,存在什么问题?需要怎么改进?
-调用函数传递的指针,是传值,所以外面的指针是没有空间的,改为传引用即可。
编程题
1、请写一个循环链表结构,并且有删除节点和增加节点的功能。
#include<iostream>
using namespace std;
typedef struct node
{
struct node * next;
int data;
}Node;
Node *createList()
{
Node * head = new Node();
head->next = nullptr;
return head;
}
void addList(Node* head,int data)
{
if(!head)//链表不存在
{
return;
}
if(!head->next)//是空链表
{
Node *node = new Node();
node->next = node;
node->data = data;
head->next = node;
}
else if(head->next == head->next->next)//只有一个
{
Node *node = new Node();
node->next = head->next;
node->data = data;
head->next->next = node;
}
else//链表已经有数据了
{
Node *p = head->next;
while(p && p->next != head->next)//找到最后一个
{
p = p->next;
}
Node *node = new Node();
node->data = data;
node->next = head->next;
p->next = node;
}
}
void printList(Node *head)
{
if(!head)
{
return;
}
if(!head->next)
{
return;
}
Node *p = head->next;
if(p->data == data)//第一个就是要删除的
{
if(head->next == p->next)
{
head->next = nullptr;
}
else
{
Node *q = head->next;
while(q && q->next != head ->next)//找到最后一个
{
q = q->next;
}
q—>next = head->next->next;
head->next = head->next->next;
}
delete p;
}
else
{
p = head->next;
while (p && p->next != head->next)//找到要删除元素的前一个元素
{
if (p->next->data == data)
{
break;
}
p = p->next;
}
if(p->next == head->next)//没有要删除的元素
{
cout<<"没有要删除的元素"<<endl;
}
Node *q = p->next;
p->next = q->next;
delete q;
}
}
int main(int argc, const char * argv[])
{
Node *head = createList();
addList(head, 1);
addList(head, 2);
addList(head, 3);
addList(head, 4);
deleteList(head, 1);
cout<<"--------------"<<endl;
printList(head);
return 0;
}
2、class A{public: int a};
假设在一个vector中有100个A数据,其中有两个数据key为A.a = 100;使用迭代器从vector中删除这两个数据。
#include <vector>
class A
{
public:
A(int i):a(i){};
int a;
};
int main(int argc, const char * argv[])
{
vector<A> v;
v.push_back(A(1));
v.push_back(A(2));
v.push_back(A(3));
v.push_back(A(4));
v.push_back(A(5));
v.push_back(A(6));
v.push_back(A(7));
v.push_back(A(1));
v.push_back(A(8));
for (int i=0; i<v.size(); i++) {
cout<<v.at(i).a<<" ";
}
cout<<endl;
v.erase(std::remove_if(v.begin(),v.end(), [](A a) { return a.a==1; } ), v.end());
for (int i=0; i<v.size(); i++) {
cout<<v.at(i).a<<" ";
}
cout<<endl;
return 0;
}