c++ - 在 C++ 中重写 = 运算符时如何初始化静态成员

标签 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();
};

我丑陋的 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)的而不是静态的,那么这样做是没有问题的:

我的线程1.x = 0;

谢谢

最佳答案

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

所以这个

TObj<int> testThread::x = 0;

基本相同

TObj<int> testThread::x(0);

关于c++ - 在 C++ 中重写 = 运算符时如何初始化静态成员,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30248870/

相关文章:

c - 什么是 C 中的 '#' 运算符?

c++ - long long是8个字节,什么意思?

c++ - 维护状态的正则表达式库,逐字符输入并在找到匹配项时返回 true

c++ - std::getline 和 eol 与 eof

c++ - 获取鼠标悬停时 ClistBox 项目的索引

c++ - 重载新的运算符(operator)问题

c++ - C++多态性与列表问题

parsing - 语法与运算符结合性之间的关系

c++ - C++ 中不等式 != 的运算符交换性

java - 为什么 arg = args[n++] 在早期编译器中比 2 个单独的语句更有效?