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


please excuse english.

i did override operator= in class. struggling initialize static member.

i get: error: conversion 'int' non-scalar type 'tobj' requested

my header file:

#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();     // bug. thank praetorian         return val;   // returns , never unlocks         m.unlock();   // not use. use lock_guard     }      ~tobj(){}  };   class ojthread { private:   public:     ojthread();     virtual void run() = 0;     void start(); }; 

my ugly cpp file:

#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. "<<localx<<"\n";     }  };  tobj<int> testthread::x = 0;  int main() {      testthread mythread;     testthread mythread2;      mythread.run();     mythread2.run();     return 0; } 

i haven't implemented threads yet please don't worry that.

i error @ line:

tobj<int> testthread::x = 0; 

if member public , not static, no problem do:

mythread1.x = 0;

thank you

you have implement constructor takes t parameter tobj. when perform assignment during object initialization calls constructor of initializing object rather operator=.

so this

tobj<int> testthread::x = 0; 

is same as

tobj<int> testthread::x(0); 

Comments

Popular posts from this blog

c++ - Difference between pre and post decrement in recursive function argument -

php - Nothing but 'run(); ' when browsing to my local project, how do I fix this? -

php - How can I echo out this array? -