c++ 语言几个坑

#include <iostream>

int main(){
        int i = 1;
        switch (i){
                case  1 :
                        int j ;
                        j = 1;
                        break;
                case 2:
                        std::cout<<j;
        }



}

  switch 支持定义变量,且其他case 可见, 所以避免问题 ,case 应该用花括号包裹

 

#include <iostream>

using namespace std;

class Base
{

public:
    Base() {}

    Base(bool arg)
    {

        foo(); // base42
    }

    virtual void foo(int i = 42)
    {

        cout << "base" << i << endl;
    }
};

class Derived : public Base
{

public:
    Derived() {}

    Derived(bool arg) : Base(arg)
    {

        foo(); // derive12
    }

    virtual void foo(int i = 12)
    {

        cout << "derived" << i << endl;
    }
};

void test1()
{

    Derived d;

    Base &b1 = d;

    Base b2 = d;

    b1.foo(); // derived42

    b2.foo(); // base42
}

void test2()
{

    Base *b = new Derived(true); // base42 derived12

    b->foo();
    delete b;
}

int main()
{

    test1();

    test2();
}

  

270da9dbe7e5:~ # ./a.out 
derived42
base42
base42
derived12
derived42

虚函数的默认参数是静态绑定的,

posted @ 2019-07-02 17:37  SnailRush  阅读(337)  评论(0编辑  收藏  举报