如何在c++中重写=操作符时初始化静态成员
How to initialize static member when = operator is overridden in c++
请原谅我的英语。
我在我的类中重写了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);
相关文章:
- 是否可以初始化不可复制类型的成员变量(或基类)
- C++使用整数的压缩数组初始化对象
- C++初始化基类
- 多成员Constexpr结构初始化
- 复制列表初始化的隐式转换的等级是多少
- 内联映射初始化的动态atexit析构函数崩溃
- 如何在C++中初始化嵌套类中的2个memeber
- 如何声明特征矩阵,然后通过嵌套循环初始化它
- 没有用于初始化C++中的变量模板的匹配构造函数
- 在未初始化映射的情况下,将值插入到映射的映射中
- C++成员初始化
- 操作符new在异常后销毁初始化的对象
- 使用三元操作符从函数返回统一初始化
- ' auto x = type{…} '初始化语法和'显式'转换操作符- clang vs gcc
- 对象初始化:初始化方法或流操作符
- c++ std::map内部类型初始化使用[]操作符
- 在c++ 11中是否可以使用new操作符初始化数组?
- c++ 11构造函数和操作符的统一初始化
- 在返回语句中统一初始化,并显式将操作符转换为bool
- 如何在c++中重写=操作符时初始化静态成员