C++计算机杂谈C语言

C++面试问题总结

2018-03-29  本文已影响49人  柚梨柚梨

指针与数组的size

int main()
{
    char b[100];
    char* p = b;
    cout << sizeof(p) << " " << sizeof(b) << " " << sizeof(*b) << endl; // 4 100 1
}

虚函数、重写、重载

#include <iostream>

using namespace std;

class Animal
{
public:
    virtual void bark() = 0; // 虚函数->多态
    virtual void bark2()
    {
        cout << "rua" << endl;
    }
    void bark3()
    {
        cout << "rua" << endl;
    }
};

class Cat : public Animal
{
public:
    void bark()  // override 重写
    {
        cout << "miao" << endl;
    }
    void bark(int a)  // overload 重载
    {
        cout << "miao" << endl;
    }

    void bark2()
    {
        cout << "miao" << endl;
    }
    void bark3()
    {
        cout << "miao" << endl;
    }
};

int main()
{
    Animal* pa;
    pa = new Cat();
    pa->bark(); // miao
    pa->bark2(); // miao
    pa->bark3(); // rua
}

public, private, protected

访问权限

啥是友元

#include <iostream>

using namespace std;

class A
{
    friend class C; //并不是成员
public:
    int pub;
private:
    int priv;
protected:
    int prot;
};

class B : public A
{
    B()
    {
        pub = 1;
        // priv = 1; can not access
        prot = 1;
    } 
};

class C // A的友元
{
    C()
    {
        A a;
        a.pub = 1;
        a.prot = 2; // 可以访问protected
        a.priv = 2; // 可以访问private
    }
};


int main()
{
    A example;
    example.pub = 2;
    // example.prot example.priv can not access
    
}

继承

上一篇下一篇

猜你喜欢

热点阅读