我几年前的工作是在TI相机中开发算法,是用C语言开发,后来接触了C++,了解了C++语言惊艳的地方,我接下来会把C++语言简单全面的介绍一下。今天这篇博文从介绍C++11和C++03不同点的视角进行介绍。这是这个主题的第二篇blog,第一篇的地址在这里。
9. override (for virutal function)
有时候你想让某个函数继承父类,但是很可能由于参数不同没有继承,c++通过override关键字强制编译器进行继承检查,如果没有发生继承,在编译时报错。
// C++ 03
class dog {
virtual void A(int);
virtual void B() const;
};
class yellowdog : public dog {
virtual void A(float); //create a new function
virtual void B(); //create a new function
};
// C++ 11
class dog {
virtual void A(int);
virtual void B() const;
};
class yellowdog : public dog {
virtual void A(float) override; //Error: no function to override
virtual void B() override; //Error: no function to override
void C() override; //Error: no function to override
};
10. final
强制不发生继承,如果有继承的动作发生,则在编译时报错。
class dog final { //no class can be derived from dog
...
};
class dog final {
virtual void bark() final; //no class can be override bark();
};
11. Compiler Generated Default Constructor
自动生成默认构造函数
class dog final {
dog(int age) {}
};
dog d1; // Error: compiler will not generate the default constructor
// C++ 11:
class dog {
dog(int age);
dog() = default; //Force compiloer to generate the default construtor
};
12. delete
强制不发生某些动作
class dog {
public:
dog(int age) {}
};
dog a(2);
dog b(3.0); // 3.0 is converted from double to int
a = b;
// C++ 11:
class dog {
dog(int age) {}
dog(double) = delete;
dog& operator=(const dog&) = delete;
};
13. constexpr
在编译阶段把函数变成宏,这对算法提速很有帮助
int arr[6]; //OK
int A() { return 3; }
int arr[A() + 3]; // Compile Error
// C++ 11
constexpr int A() { return 3; } // Forces the computation to
// happen at compile time.
int arr[A() + 3]; // Create an array if size 6
// Write faster program with constexpr
constexpr int cubed(int x) (return x*x*x);
int y = cubed(1789); //
computed at compile time
14. New String Literals
// C++ 03
char* a = "string";
// C++ 11:
char* a = u8"1我爱你"; //to define an UTF-8 string
char16_t* b = u"1我爱你"; //to define an UTF-16 string
char32_t* c = U"1我爱你"; //to define an UTF-32 string
char* d = R"--string--";
15. Lambda function
lambda这个关键字还是比较重要,很多git上代码都用lambda函数,至少这样开起来很厉害。
template<typename func>
void filter(func f, vector<int> arr) {
for (auto i : arr) {
if (f(i))
cout << i << "";
}
}
cout << [](int x, int y) {return x + y; }(3, 4) << endl; // Output 7
auto f = [](int x, int y) {return x + y; };
cout << f(3, 4) << endl; // Output 7
vector<int> v = { 1,2,3,4,5,6 };
filter([](int x) { return (x > 3); }, v); // Out 4 5 6
filter([](int x) { return (x > 2 && x<5); }, v); // Out 3 4
int y = 4;
filter([&](int x) {return (x>y); }, v); // Out 5 6
//Note: [&] tells compilter that we want variable capture
最后的话:
这篇文章发布在CSDN/蓝色的杯子, 没事多留言,让我们一起爱智求真吧.我的邮箱wisdomfriend@126.com