一、在Qt中使用c++11
在Qt Creator中使用C++11, 需要在.pro中添加下面的语句
CONFIG += c++11
注意:只有使用的编辑器支持C++11才能使用C++11的特性。
二、auto和decltype关键字
auto:自动判断变量的类型。
decltype:判断一个表达式的类型。
例:
QMap<QString, int> nMap;
nMap.insert("a", 1);
nMap.insert("b", 2);
nMap.insert("c", 3);
// 不用C++11的声明形式
QMap<QString, int>::Iterator itor = nMap.begin();
// 使用C++11的形式
auto itor = nMap.begin();
for (; itor != nMap.end(); ++itor)
qDebug() << itor.value();
// nItor的类型与itor一致,均为迭代器
decltype(itor) nItor = nMap.begin();
qDebug() << nItor.value();
三、override和final
override:派生类中重写基类中的虚函数, 派生类中使用此关键字,若该函数不是重写,则编译时报错。
final:派生类中不能重写基类中的虚函数,基类中使用此关键字,若派生类中重写此函数则编译时报错。
例:
构建一个Base基类:func函数可以被子类重写,func2函数不能被子类重写。
class Base : public QObject
{
public:
Base(){
}
virtual ~Base()
{
}
protected:
virtual int func(int num1, int num2){
return num1 * num2;
}
virtual int func2(int num1, int num2) final{
return num1 * num2;
}
};
使用关键字override:
class ChildObject : public Base
{
public:
ChildObject();
~ChildObject();
protected:
int func(int num1, int num2) override; // 若Base中的func不是虚函数,则报错
};
使用关键字final:
class ChildObject2 : public Base
{
public:
ChildObject2();
~ChildObject2();
protected:
int func2(int num1, int num2); // 编译报错
};
四、nullptr和for
1、nullptr和NULL
nullptr标识空指针,不能转成整形;而NULL可以被转成整形
2、for语句和foreach
QList<int> nList;
nList.push_back(11);
nList.push_back(12);
nList.push_back(13);
Qt中的foreach函数:
foreach (auto i, nList)
qDebug() << i;
C++11中
for (auto i : nList)
qDebug() << i;
五、lambda表达式
lambda表达式的四种形式
[ capture ] ( params ) mutable exception attribute -> ret { body }
|
略
[ capture ] ( params ) -> ret { body }
|
capture 捕获对象,
- [a,&b] a变量以值的方式呗捕获,b以引用的方式被捕获。
- [this] 以值的方式捕获 this 指针。
- [&] 以引用的方式捕获所有的外部自动变量。
- [=] 以值的方式捕获所有的外部自动变量。
- [] 不捕获外部的任何变量。
params 传递的参数
ret返回值的类型
{body}函数体
[ capture ] ( params ) { body }
|
[ capture ] { body }
|
auto func1 = [](int i) { return i+4; };
std::cout << "func1: " << func1(6) << '\n'; // 结果为func1: 10
std::cout << "func1: " << [](int i) { return i+4; }(6) << '\n'; // 结果为func1: 10
Qt5中的QObject::connect支持lambda表达式的信号与槽的链接形式
QLineEdit *nEdit1 = new QLineEdit;
QLineEdit *nEdit2 = new QLineEdit;
QVBoxLayout *layout = new QVBoxLayout;
this->setLayout(layout);
layout->addWidget(nEdit1);
layout->addWidget(nEdit2);
layout->addStretch();
目的是nEdit1输入字母 nEdit2中同步为大写的
QObject::connect(nEdit1, &QLineEdit::textChanged, [=](const QString &text){
nEdit2->setText(text.toUpper());
});