首页 > 代码库 > c++学习2

c++学习2

  • C++多态
  • #include <iostream>
    #include <iomanip>
    using namespace std;
    
    class Base {
    public:
        virtual void f() { cout << "base" << endl; }
    };
    class Derived : public Base{
    public:
        void f() { cout << "derived" << endl; }
    };
    class Base2 {
    public:
        virtual void g() { cout << "base2 process g" << endl; } // dynamic_cast only work under polymorphic settings
    };
    class Derived2 : public Base2{
    public:
        void f() { cout << "derived2" << endl; }
    };
    
    int main() {
        /*
        Base *b = new Derived;
        b->f(); //base
    
        Base *b = new Derived;
        Derived *a = static_cast<Derived *>(b);
        a->f(); //derived
    
        Base *b = new Derived;
        b->f(); //derived, derived overwrite base in virtual table
        Derived *a = dynamic_cast<Derived *>(b);
        a->f(); //derived, same with b->f()
     */
        Base2 *b = new Derived2;
        //b->f(); // compile error
        Derived2 *a = dynamic_cast<Derived2 *>(b);
        a->f(); //derived2, same with b->f()
        return 0;
    }
  • 可调用函数, 匿名函数
  • auto f = [](int a, int b){return a + b;};
    cout << f(1,2) << endl; //3
    cout << [](int a, int b){return a + b;}(1,2) << endl; //3
    int a = 0; int b = 0; int c = 0;
    
    //cout << [=](int a, int b){c = 1; return a + b;}(1,2) << "\t" << c << endl;
    // error: cannot assign to a variable captured by copy in a non-mutable lambda
    //cout << [](int a, int b){int c = 1; return a + b;}(1,2) << "\t" << c << a << endl; //3 \t 0
    
    cout << [&](int a, int b){c = 1; return a + b;}(1,2) << "\t" << c << "\t" << a << endl; //3 \t 1
    cout << [&c](int a, int b){c = 1; return a + b;}(1,2) << "\t" << c << endl; //3 \t 1
    

      

c++学习2