趨勢的C++面試題

來源:互聯網
上載者:User
    1.
    class A{
    public:
            A() {func(0);};
            virtual void func(int data) {printf("A1 :%d\n",data);}
            virtual void func(int data) const {printf("A2 :%d\n",data);}
            void func(char *str) {printf("A3 :(%s)\n",str);}
    };

    class B:public A{
    public:
            void func()    {printf("B1 :%s\n","");}
            void func(int data)    {printf("B2 :%d\n",data);}
            void func(char *str)    {printf("B3 :(%s)\n",str);}
    };

    int main()
    {
            A *pA;
            B b;
            const A *pcA;

            pA=&b;
            pA->func(1);
            pA->func("test");
            A().func(1);
            pcA=&b;
            pcA->func(2);
            return 0;
    }

    程式啟動並執行結果:
    A1 :0
    B2 :1
    A3 :(test)
    A1 :0
    A1 :1
    A2 :2

    1) 基類的指標指向衍生類別對象:那麼該指標只能夠調用基類所定義的函數,但是如果該函數為虛函數,則調用該衍生類別自己的成員函數。(B2 :1)
    2) 如果以衍生類別的指標指向基類對象,則必須事先做明顯的轉型操作,但是這種做法很危險。

    2.
    template
    void func(const int &t)
    {
             cout<<t+100<<endl;
    }

    template
    void func(const T&t)
    {
             cout<<t;
    }

    int main()
    {
             func(10.3);
             func(1000);

             return 0;
    }

    程式運行結果:
    10.3
    1000

    如果上述函數改為
    void func(const int &t)
    {
             cout<<t+100<<endl;
    }

    template
    void func(const T&t)
    {
             cout<<t<<endl;
    }

    int main()
    {
             func(10.3);
             func(1000);

             return 0;
    }

    則程式的運行結果為:
    10.3
    1100

    如果使用函數的非模板形式,不能在前面加上template關鍵字。

    3、改錯:
    class klass
    {
    public:
               klass(){}
    private:
               ~klass(){}
               void func(int n){
                       cout<<"klass!!"<<endl;
                }
    public:
               void test()
              {
                      func(100);
              }
    };

    int main()
    {
             klass k;
             k.test();

             return 0;
    }
    運行後程式顯示:error C2248: 'klass::~klass' : cannot access private member declared in class 'klass'
    證明解構函式的屬性必須為public。
    但是,如果把klass k改為klass* pk; pk=new klass; pk->test();程式通過,但是klass不能釋放.

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.