静止的并不是一成不变的
Static... not really static
我一直在做一个项目,我发现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
,而在已发布的示例中从未使用过该关键字。
相关文章:
- 为不同配置设置MSVC_RUNTIME_LIBRARY的正确方法是什么
- enum是C++中的宏变量还是整数变量
- 检查输入是否不是整数或数字
- 什么时候在C++中返回常量引用是个好主意
- 如果C++类在类方法中具有动态分配,但没有构造函数/析构函数或任何非静态成员,那么它仍然是POD类型吗
- boost beast Websocket Multi Request Server/Client 并不是真正的 mul
- 虽然我添加了boost库,但Eclipse并不是用C++构建的.为什么
- 是否有任何版本的C++(甚至是试行标准)是"throw()"并不意味着"cannot throw, ever"?
- 将对象传递给函数并不是导致构造函数调用
- lua_gettiop返回0,但堆栈的行为并不像是空的
- random_shuffle并不是真的随机
- SFML 2.0:键盘::是按键并不总是正确返回
- 从catch块调用异常类中的函数并不是打印从try块传递的值
- 哪些窗口事件会影响 MDIGetActive()?导致OnMDIActivate()的事件并不是唯一的事件
- 是函数返回的临时对象,并不总是 r 值
- 并不是每次都调用CPrintDialog::OnInitDialog
- 阶乘并不是对所有值都有效
- 静止的并不是一成不变的
- C++ 随机引擎并不是真正的随机
- 在c++中使用均匀实分布生成的随机数并不是真正均匀分布的