VS2017報錯:未提供初始值設定項


今天在使用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;
}


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM