1. 程式人生 > >C++經典面試題匯總

C++經典面試題匯總

代碼 get child pre delet 函數調用 列表 code pub

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)多態:根據實際的對象類型決定函數調用語句的具體調用目標。

C++經典面試題匯總