2016-11-24 7 views
-3

すべてのアプリケーションクラスからオブジェクトにアクセスできるようにしたいと考えています。しかしだから私:すべてのアプリケーションクラスで1つのオブジェクトにアクセス可能

#include <iostream> 

using namespace std; 

class MyClass { 
public: 
    MyClass(){} 
    int id(){return -1;} 
}; 

extern const MyClass myClass; 

int main() { 
    cout << myClass.id(); 
    return 0; 
} 

そして、どこでも、私は、私はやることが必要になります。

にextern constのMyClassのMYCLASS。以下のような

とそれを使用し、:

cout << myClass.id(); 

しかし、私は間違っていました。私は私ではなく、static MyClass myClass;を行うことができると思い

error: passing 'const MyClass' as 'this' argument of 'int MyClass::id()' discards qualifiers [-fpermissive] 

:それはエラーが返されます。そして、私は多かれ少なかれ同じ機能を持つでしょう。

ベスト/正しいアプローチは何ですか?

+2

'int id()const {return -1; } ' –

+1

エラーメッセージは、constオブジェクトで非constメソッド' id() 'を呼び出していると言います。 –

答えて

3

いずれ宣言と定義constを破棄:

extern /* const */ MyClass myClass; 
    // ^^^^^^^^^^^ 

又はid()機能constます

int id() const {return -1;} 
     // ^^^^^ 

I Guess I could do static MyClass myClass;, instead. And so I will have more or less the same functionality.

static変数は、クラスのメンバーとしてのみ意味をなすであろう。

What's the best/correct approach?

方が良いシングルトンパターン使用したクラスのインスタンスを1つだけが存在することを確認したい場合は、次の

class MyClass { 
    MyClass(){} 
public: 
    static Myclass& instance() { 
     static MyClass theInstance; 
     return theInstance; 
    } 
    int id(){return -1;} 
}; 

だからあなたはどこにでも、例えば使用してから、単一のクラスのインスタンスにアクセスすることができますがMyClass::instance().id()、および他のインスタンスの構築を禁じます。

+0

メソッド 'const'を作成すると、' myClass'への未定義参照があります。 – KcFnMi

+1

@KcFnMi別のファイルのグローバルな 'myClass'変数の定義を忘れてしまいました。 –