2015-05-14 57 views
1

请原谅我的英文。如何初始化静态成员,当=运算符在C++中被覆盖时

我没有在我的课上覆盖operator =。现在我正在努力初始化一个静态成员。

我得到: 错误:转换,从 '诠释' 非标量型 '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; 

如果该成员是公开的,而不是一成不变的,它是没有问题的事::

我在该行得到错误

myThread1.x = 0;

谢谢

+0

你还没告诉编译器如何把一个'int'成'TObj ',重新表述错误。 – chris

+1

'operator T(){ m.lock(); return val; m.unlock();你的互斥锁被锁定一次,永远不会解锁。使用['lock_guard'](http://en.cppreference.com/w/cpp/thread/lock_guard)而不是手动锁定和解锁。 – Praetorian

+0

谢谢。我将添加评论以表明这一点。 – Makketronix

回答

7

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

所以这

TObj<int> testThread::x = 0; 

是基本相同

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

非常感谢您的先生。 – Makketronix