首页 > 代码库 > 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
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。