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

How to initialize static member when = operator is overridden in c++

本文关键字:操作符 初始化 静态成员 重写 c++      更新时间:2023-10-16

请原谅我的英语。

我在我的类中重写了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();
};

我的丑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;
}

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

我得到错误在行:

TObj<int> testThread::x = 0;

如果该成员是public而不是static,则执行以下操作是没有问题的:

myThread1。X = 0;

谢谢

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

TObj<int> testThread::x = 0;

基本相同
TObj<int> testThread::x(0);