在c ++中重写= operator时如何初始化静态成员

Mak*_*nix 1 c++ operator-keyword

请原谅我的英语.

我在我的班级中覆盖了operator =.现在我正在努力初始化一个静态成员.

我得到:错误:从'int'转换为非标量类型'TObj'请求

我的头文件:

#include <mutex>

template<typename T>
class TObj{
private:
    std::mutex m;
public:
    T val;
    // = coperation
     TObj& operator=(const T& rhs){
       m.lock();
       val = rhs;
       m.unlock();
       return *this;
    }

    operator T(){
        m.lock();     // THIS IS A BUG. Thank you Praetorian
        return val;   // RETURNS AND NEVER UNLOCKS
        m.unlock();   // DO NOT USE. Use lock_guard
    }

    ~TObj(){}

};


class OJThread
{
private:


public:
    OJThread();
    virtual void run() = 0;
    void start();
};
Run Code Online (Sandbox Code Playgroud)

我丑陋的cpp文件:

#include <iostream>
#include "ojthread.h"


using namespace std;

class testThread: OJThread{

public:
    static TObj<int> x;
    int localX;
    testThread(){
        localX = x;
    }

    void run(){
        cout<<"Hello World. This is "<<localX<<"\n";
    }

};

TObj<int> testThread::x = 0;

int main()
{

    testThread myThread;
    testThread myThread2;

    myThread.run();
    myThread2.run();
    return 0;
}
Run Code Online (Sandbox Code Playgroud)

我还没有实现线程,所以请不要担心.

我在行上得到错误:

TObj<int> testThread::x = 0;
Run Code Online (Sandbox Code Playgroud)

如果这个成员是公共的而不是静态的,那么这样做是没有问题的:

myThread1.x = 0;

谢谢

Den*_*rim 7

您必须实现一个构造函数,该构造函数T作为参数TObj.在对象初始化期间执行赋值时,它会调用初始化对象的构造函数而不是operator=.

所以这

TObj<int> testThread::x = 0;
Run Code Online (Sandbox Code Playgroud)

基本上是一样的

TObj<int> testThread::x(0);
Run Code Online (Sandbox Code Playgroud)