静止的并不是一成不变的

Static... not really static

本文关键字:一成不变 并不是 静止      更新时间:2023-10-16

我一直在做一个项目,我发现static关键字有时会有点乱。

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

下面是我一直在尝试做的一个例子:

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.hp:

#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;
}

结果是:

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

静电有什么我不懂的地方吗?我应该制作一个接口文件(带有名称空间interface)吗?请帮帮我。

谢谢。

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

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

至于static,我在您引用的代码中没有看到任何静态内容。

使用可以获得您想要的效果

static int w, h;

但你的想法似乎不止于此。是否允许一次存在多个Screen?您是否希望Class之外的其他类(不要将您的类称为Class)能够访问Screen?这可能是Singleton模式的作业,也可能是嵌套类之类的作业。

没有"静态类"这回事

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

class Foo
{
};
static Foo my_foo_;

或者,您可以在类中使用静态方法。。。

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

后者是我怀疑你实际上想做的

请注意,为了获得此功能,您实际上必须使用关键字static,而在已发布的示例中从未使用过该关键字。