gpt4 book ai didi

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

转载 作者:太空宇宙 更新时间:2023-11-03 10:43:02 26 4
gpt4 key购买 nike

请原谅我的英语。

我确实在类里面重写了 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/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com