2011-06-03 38 views
-2

我一直在做一个项目,我发现了static关键字有时可能是一种乱。静态...不是真的静态

我的项目使用的库ncurses的。我想要做的是获得我的屏幕的高度,然后打印它。一旦我的屏幕初始化,静态类(屏幕)应始终具有相同的高度和宽度。

这里是什么,我一直试图做一个例子:

class.hpp:

#ifndef CLASS_H 
#define CLASS_H 

#include <iostream> 

#include "screen.hpp" 

class Class{ 
public: 
     Class(){ 
      std::cout << "Class: " << std::endl; 
     } 
     virtual ~Class(){} 
}; 

#endif //CLASS_H 

screen.hpp:

#ifndef SCREEN_H 
#define SCREEN_H 

#include <curses.h> 
#include <signal.h> 
#include <curses.h> 

class Screen{ 
public: 
    Screen(); 
    virtual ~Screen(); 

    void Init(); 
    void Close(); 

    int getW() const; 
    int getH() const; 

private: 
    int w, h; 
}; 

static Screen screen; 

#endif // SCREEN_H 

main.cpp中:

#include <iostream> 
#include "screen.hpp" 
#include "class.cpp" 

int main(int argc, char** argv){ 
    screen.Init(); 
    screen.Close(); //I just wanted to set my H and W in screen 

    std::cout << "main: " << screen.getH() << std::endl; 

    Class classa(); //Will print the screen H in the constructor 

    return 0; 
} 

这是resul t:

iDentity:~$ g++ -Wall -g main.cpp screen.cpp class.cpp -lncurses 
iDentity:~$ ./a.out 
main: 24 
Class: 0 
iDentity:~$ 

有什么我不明白的静态?我应该创建一个接口文件(使用名称空间接口)吗?请帮帮我。

谢谢。

+4

我必须失去了一些东西。我无法找到你的代码中的static关键字...... – jwismar 2011-06-03 16:06:55

+0

呃,你没有实际使用'static'任何有... – bdonlan 2011-06-03 16:07:25

+2

另外'Class classa();'是一个函数声明。 – 2011-06-03 16:07:56

回答

2
Class classa(); //Will print the screen H in the constructor 

不能打印任何东西,因为它不声明变量,因此不会调用构造函数。它声明功能classa它没有任何参数,并返回Class

至于static,我看不到任何东西在你的报价代码的静态。

+1

我认为你的意思是它没有声明一个对象或实例, – jwismar 2011-06-03 16:10:35

+0

@ jwismar:是的。这是一个错字。 – Nawaz 2011-06-03 16:11:02

0

你可以得到你所要寻找的

static int w, h; 

的效果,但你似乎多了个心眼多。你想让更多的一个Screen存在吗?而且你想其他类旁边Class打电话给你Class类)有机会获得一个Screen?这可能是Singleton模式或嵌套类或类似的工作。

0

有没有这样的事,作为一个“静态类”。

你可以有一个类的静态实例...

class Foo 
{ 
}; 

static Foo my_foo_; 

或者你可以有你的类中的静态方法...

class Foo 
{ 
public: 
    static void Bar() {}; 
}; 

int main() 
{ 
    Foo::Bar(); 
} 

后者是我怀疑你”实际上正在努力去做。

注意的是,为了得到这个功能你确实有使用关键字static,你从来没有在发布中这么做。