#include <iostream>
using namespace std;
class background_task
{
public:
background_task()
{
cout << "默认构造" << this->m_num << endl;
}
background_task(int num)
{
this->m_num = num;
cout << "带参构造" << this->m_num << endl;
}
//void operator()()
//{
// cout << "background_task.....operator..." << endl;
//}
private:
int m_num = 20;
};
int main()
{
background_task b1; //1
background_task b2(); //2
background_task b3(10); //3
// 无区别
background_task *p1 = new background_task;
background_task *p2 = new background_task();
//对于内置类型而言,加括号是进行了初始化,不加是未进行初始化
int *p1Int = new int();
int *p2Int = new int;
//b1();
background_task(); //匿名对象
background_task(199); //匿名对象
background_task bts1 = background_task(); // 同background_task b1;
background_task bts2 = background_task(10);// 同background_task b3(10);;
return 0;
}
違いの3種類の上記で定義された分析の宣言変数:
図1は、自動的にbackground_taskなしコンストラクタ関数パラメータを呼び出し、ローカル変数B1を定義します。
2は、特別な注意:ここでは、関数名の関数の戻り値はちょうど声明ではなく、実装background_task b2のある宣言と同じです。
3、ローカル変数B3の定義、パラメータ化コンストラクタは自動的にクラスbackground_taskを呼び出します
注意:
コードセクション内のコメントは、特別な注意が必要です::
この場合、B1に()関数がオーバーロードと呼ばれる関数ボイド演算子()()
時々、私たちは、関数のパラメータに渡された匿名オブジェクトを使用していますが、時々、予想とは異なります。
#include <iostream>
#include <thread>
using namespace std;
class background_task
{
public:
background_task()
{
cout << "默认构造" << this->m_num << endl;
}
background_task(int num)
{
this->m_num = num;
cout << "带参构造" << this->m_num << endl;
}
void operator()()
{
cout << "background_task...Threadid:" << this_thread::get_id() << endl;
cout << "Threadnum:" << this->m_num << endl;
}
private:
int m_num = 20;
};
int main()
{
//那么此时编译器会把background_task()解释为函数声明background_task (__cdecl *)(void)
//std::thread t(background_task());
// 解决上述问题两种方案
std::thread t1((background_task()));
std::thread t2{background_task(100)};
int numA = 2000;
std::thread t3([&](){
cout << "lambda" << numA << endl;
numA = 1000;
});
t1.join();
t2.join();
t3.join();
cout << "main numA=" << numA;
return 0;
}