2012-04-06 6 views
0
class classe(){ 
public: 
    int key; 

    static void *funct(void *context){ 
     printf("Output: %d, ", key); 
    } 

    void Go(){ 
     classe c = static_cast<this>(context); //<- This doesn't work, Context of this-> goes here 
     pthread_create(&t, NULL, &classe::funct, c); 
    } 
}; 

int main(){ 

    classe c; 
    c.key = 15; 
    c.Go(); 

    c.key = 18; 
    c.Go(); 
} 

出力はOutput: 15, Output: 18,あるべきクラスポインタへの代入、事はthisのコンテキストがエラーをスロー取得することです。は「この」内部クラスのコンテキストを取得とするtheClass *

誰かがこれを修正する方法を知っていますか?

答えて

2

私はあなたのコードでいくつかの問題が見ることができます:

まず、static_cast<><>でタイプを必要とし、変数(そうでないタイプ)のようなthis行為。 thisのタイプは、classe内にclasse*classeオブジェクトへのポインタ)です。

第2に、classe:Go()で利用可能なcontextはありません。その名前でclasse::fuct()のパラメーターがありますが、使用する場所では使用できません。

第3に、pthread_create()はフリー関数(または静的メンバー関数)を前提とし、クラスメンバー関数(classe::funct)を提供します。クラスメンバ関数は、暗黙のパラメータ== thisのようなもの)を処理するオブジェクトを必要とします。

static void *funct(void *key){ // funct is now a free function, all data is provided to it 
    printf("Output: %d, ", *static_cast<int*>(key)); 
} 

class classe() 
{ 
public: 
    int key; 

    void Go(){ 
    pthread t; 
    pthread_create(&t, NULL, funct, &key); // pass (address of) key to funct 
    } 
}; 

int main(){ 

    classe c; 
    c.key = 15; 
    c.Go(); 

    c.key = 18; 
    c.Go(); 
} 
+0

フリー関数である必要はありませんが、静的メンバーはうまく動作します。 – Josh

+0

ありがとうございました – Attila

1

まず、contextをどこかに定義する必要があります。次に、thisは、メンバー関数が呼び出されているオブジェクトへのポインタを表すキーワードです。 static_castには、テンプレート引数にタイプが必要です。 static_cast<this>static_cast<classe*>に置き換え、cのタイプをclasse *に変更して、ステートメントをコンパイルします。

0

あなたが主要部品の一部が行く場所について少し混乱しているようだ。また、あなたが試みることができるあなたがpthread_create()

に渡すことができclasse::Go()で定義されてtを持っていません。ここでは、あなたが望むものの大部分を占めると思う骨格があります。

class classe { 
    public: 
     classe(int k) : key(k) { } 

     void Go() { 
      // where does "t" come from? 
      pthread_create(&t, NULL, &funct, static_cast<void*>(this)); 
     } 

    private: 
     int key; 

     static void* funct(void* context) { 
      classe* self = static_cast<classe*>(context); 
      printf("Output: %d ", self->key); 
      return 0; // not sure this is what you want 
     } 
}; 

int main() { 
    classe c(15); 
    c.Go(); 
} 
1

このような何か試してみてください:

#include <stdio.h> 
#include <pthread.h> 

class classe 
{ 
public: 
    int key; 

    static void* funct(void *context) 
    { 
     classe* c = static_cast<classe*>(context); 
     printf("Output: %d, ", c->key); 
     return context; 
    } 

    void Go() 
    { 
     pthread_t t; 
     pthread_create(&t, NULL, &classe::funct, this); 
     void* p = 0; 
     pthread_join(t, &p); 
    } 
}; 

int main() 
{ 
    classe c; 
    c.key = 15; 
    c.Go(); 

    c.key = 18; 
    c.Go(); 
    return 0; 
} 

を私は適切な機能にコンテキストを使用して移動し、プログラムが終了しないようにスレッドが実行する機会を持つ前にpthread_joinをを追加しました。

関連する問題