2016-11-24 70 views
-3

我希望在所有应用程序类中都可以访问对象。所以,我虽然:在我的所有应用程序类中都可以访问一个对象

#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(); 

可是,我错了。这返回错误:

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

我猜我可以做static MyClass myClass;,而不是。所以我会有或多或少相同的功能。

什么是最好的/正确的方法?

+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?

如果你想确保存在的类只有一个实例更好地运用Singleton模式

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'变量的定义。 –

相关问题