码迷,mamicode.com
首页 > 编程语言 > 详细

c++学习2

时间:2017-03-22 00:18:51      阅读:189      评论:0      收藏:0      [点我收藏+]

标签:mpi   ast   匿名函数   include   set   static   overwrite   log   void   

  • 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

标签:mpi   ast   匿名函数   include   set   static   overwrite   log   void   

原文地址:http://www.cnblogs.com/sylar120/p/6597578.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!