zoukankan      html  css  js  c++  java
  • 求职面试--复习笔记2

    1、在c++中,class和struct 的区别是什么?参考:点击打开链接

    2、初始化列表和构造函数初始化的区别是什么?

    3、C++中虚继承和继承的区别是什么?参考:点击打开链接

    4、虚函数的实现原理?

    事例代码:

    #include <iostream>
    using namespace std;
    
    
    class Base
    {
    public:
    	virtual void f()
    	{
    		cout << "Base::f" <<endl;
    	}
    
    	virtual void g()
    	{
    		cout << "Base::g" <<endl;
    	}
    
    	virtual void h()
    	{
    		cout << "Base::h" <<endl;
    	}
    };
    
    int main()
    {
    	typedef void (*Fun)(void);
    	Base b;
    	Fun pFun = NULL;
    	cout << "虚函数表的地址:" << (int*)(&b) <<endl;
    	cout << "虚函数表----第一个函数地址:" << (int*)*(int*)(&b) <<endl;
    	pFun = (Fun)*((int*)*(int*)(&b)+1);
    	pFun();
    	return 0;
    }
    

    5、什么函数可以声明为虚函数?

    除构造函数、内联函数之外的非静态成员函数都可以声明为虚函数。

    6、析构函数通常声明为虚函数,为什么?

    有时候必须将析构函数声明为虚函数,基类指针指向派生类,对基类指针delete时,如果不定义成虚函数,派生类中派生的那部分无法被析构。示例代码如下:

    #include <iostream>
    using namespace std;
    
    class CPerson
    {
    public:
    	virtual ~CPerson();
    protected:
    	char* m_lpszName;
    	char* m_lpszSex;
    };
    
    class CStudent:public CPerson
    {
    public:
    	virtual ~CStudent();
    protected:
    	int m_iNumber;
    };
    
    CPerson::~CPerson()
    {
    	cout << "~CPerson!" <<endl;
    }
    
    CStudent::~CStudent()
    {
    	cout << "~CStudent!" <<endl;
    }
    
    int main()
    {
    	CPerson *p = new CStudent;
    	if (NULL == p)
    	{
    		exit(0);
    	}
    	delete p;
    	cout << "CStudent对象已经完成析构"<<endl;
    	return 0;
    }
    

    7、main()主函数执行完毕之后,是否可以再执行一段代码?

    可以,使用_onexit()函数注册一个函数,这个函数会在main()完成之后再次执行。示例程序如下:

    #include <stdio.h>
    #include <stdlib.h>
    
    int fun()
    {
    	printf("after main
    ");
    	return 0;
    }
    
    int main()
    {
    	_onexit(fun);
    	printf("This is excuted first
    ");
    	return 0;
    }
    


  • 相关阅读:
    LeeCode 1497. 检查数组对是否可以被 k 整除
    LeetCode 1503. 所有蚂蚁掉下来前的最后一刻
    双指针算法
    最短送餐路程计算, 美团笔试题2020
    最短路算法dijkstra算法
    寻找最小子字符串, 美团笔试题2020
    最大矩形, 统计全1子矩阵
    拼凑硬币, 腾讯
    7月15日
    7月14日
  • 原文地址:https://www.cnblogs.com/javaadu/p/11742641.html
Copyright © 2011-2022 走看看