今天在使用VS2017寫程序時,報錯:

出錯的代碼如下:
#include "pch.h"
#include <iostream>
#include <thread>
using namespace std;
class TA
{
public:
TA(int &i);
~TA();
//TA(const TA& ta); //拷貝構造函數
void operator()()
{
cout << "我的線程開始執行了" << endl;
cout << "我的線程結束了" << endl;
}
private:
int &m_i;
};
TA::TA(int &i)
{
this->m_i = i;
cout << "TA的構造函數" << endl;
}
TA::~TA()
{
cout << "TA的析構函數" << endl;
}
//
//TA::TA(const TA &ta)
//{
// this->m_i = ta;
//}
int main()
{
int i = 6;
TA ta(i);
thread mytobj(ta);
mytobj.join();
cout << "主線程執行結束" << endl;
return 0;
}
在網上查找資料后找到原因:
可以初始化const對象或引用類型的對象,但不能對他們賦值。在開始執行構造函數的函數體之前,必須完成初始化。初始化const或引用類型數據成員的唯一機會是在構造函數初始化列表中。
也就是說在類TA中聲明了引用m_i,只能在構造函數初始化列表中進行初始化。
將上面的代碼修改如下后錯誤消失:
#include "pch.h"
#include <iostream>
#include <thread>
using namespace std;
class TA
{
public:
TA(int &i) :m_i(i) {};
~TA();
//TA(const TA& ta); //拷貝構造函數
void operator()()
{
cout << "我的線程開始執行了" << endl;
cout << "我的線程結束了" << endl;
}
private:
int &m_i;
};
TA::~TA()
{
cout << "TA的析構函數" << endl;
}
//
//TA::TA(const TA &ta)
//{
// this->m_i = ta;
//}
int main()
{
int i = 6;
TA ta(i);
thread mytobj(ta);
mytobj.join();
cout << "主線程執行結束" << endl;
return 0;
}
- 參考資料:
1 《必須在構造函數基/成員初始值設定項列表中初始化》 https://www.cnblogs.com/zzyoucan/p/3570493.html?utm_source=tuicool&utm_medium=referral
