C++经典面试题汇总

1. 下面代码输出什么?为什么?(初始化列表)

#include<iostream>

using namespace std;

class Test
{
    int m_i;
    int m_j;
public:
    Test(int v): m_j(v), m_i(m_j)
    {
        
    }
    int getI()
    {
        return m_i;
    }
    int getJ()
    {
        return m_j;
    }
};

int main()
{
    Test t1(1);
    Test t2(2);
    
    cout << t1.getI() << " " << t1.getJ() << endl;
    cout << t2.getI() << " " << t2.getJ() << endl;
    
    return 0;
}

① 答案:

随机数 1

随机数 2

② 核心提示:

(1)成员变量的初始化顺序与声明顺序有关,与初始化列别顺序无关

2. 下面程序输出什么?为什么?(多态)

#include <iostream>

using namespace std;

class Base
{
public:
    virtual void func()
    {
        cout << "Base::func" << endl;
    }
};

class Child : public Base
{
public:
    void func()
    {
        cout << "Child::func" << endl;
    }
};

int main()
{
    Base* pb = new Base();
    pb->func();
    
    Child* pc = (Child*)pb;
    pc->func();
    
    delete pc;
    
    pb = new Child();
    pb->func();
    
    pc = (Child*)pb;
    pc->func();
    
    return 0;
}

① 答案:

Base::func
Base::func
Child::func
Child::func

② 核心提示:

(1)多态:根据实际的对象类型决定函数调用语句的具体调用目标。

猜你喜欢

转载自www.cnblogs.com/wulei0630/p/9783632.html
今日推荐