C++常见笔试题

来源:互联网 发布:曾舜晞粤读软件 编辑:程序博客网 时间:2024/06/06 04:05

Q1. 下面程序的输出结果是?

class A{    public:        A(){            cout << "A()" << endl;        }        ~A(){            cout << "~A()" << endl;        }                virtual void fun(){            cout << "A:fun()" << endl;        }};class B: public A{    public:        B(){            cout << "B()" << endl;        }        ~B(){            cout << "~B()" << endl;        }        virtual void fun(){            cout << "B:fun()" << endl;        }};class C: public B{    public:        C(){            cout << "C()" << endl;        }        ~C(){            cout << "~C()" << endl;        }private:        virtual void fun(){            cout << "C:fun()" << endl;        }};int main(){    B b = B();    B *c = new C();    c->fun();    delete c;}
A1.参考答案:

A()B()A()B()C()C:fun()~B()~A()~B()~A()

Q2:设计一个只能在堆内存上实例化的类和一个只能在栈内存上实例化的类,否则出现编译错误。

A2:不能在栈上实例化,而只能在堆上实例化,可以将析构函数私有化,防止自动调用析构函数,必须手动调用;

class CHeapOnly{public:    CHeapOnly()    {        cout << "Constructor of CHeapOnly!" << endl;    }    void Destroy() const    {        delete this;    }private:    ~CHeapOnly()    {        cout << "Destructor of CHeapOnly!" << endl;    }};
只能在栈内存上实例化,不能在堆内存上实例化,将new和delete操作符私有化。

class CStackOnly{public:    CStackOnly()    {        cout << "Constructor of CStackOnly!" << endl;    }    ~CStackOnly()    {        cout << "Destrucotr of CStackOnly!" << endl;    }private:    void* operator new(size_t size)    {    }    void operator delete(void * ptr)    {    }};




0 0