VS2017 given: Unavailable initializer

Today, when writing programs using VS2017, given:

Error code is as follows:

#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;
}

After the Internet to find reasons to find information:

You can initialize a const object or reference object type, but you can not assign to them. Before beginning the body of the constructor must be initialized. Initialization only chance const or reference data members in the constructor initialization list.

That statement references m_i TA in the class, it can only be initialized in the constructor initialization list.

The above code is modified as follows after the error disappears:

#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;
}

Guess you like

Origin www.cnblogs.com/Manual-Linux/p/11544996.html