c++使用ncurses库重复函数名称

标签 c++ namespaces ncurses

我正在使用 ncurses 库实现俄罗斯方 block 游戏。 我试图实现 key 处理程序类,它具有名为 timeout 和 getch 的成员函数。

key_handler.h

#ifndef KEY_HANDLER_H_
#define KEY_HANDLER_H_

#include "tetris.h"
#include <ncurses.h>

namespace tetris {
  class KeyHandler {
    public:
      KeyHandler();
      ~KeyHandler();
      void timeout(int timeout_ms);
      int getch();
    private:
      WINDOW *window_;
      int timeout_ms_;
  };
}
#endif

key 处理程序.cpp

#include "key_handler.h"

using tetris::KeyHandler;

KeyHandler::KeyHandler() {
  window_ = newwin(0, 0, 0, 0);
  timeout_ms_ = 1000; // ms
  curs_set(0);
  cbreak();
  noecho();
  keypad(window_, TRUE);
}

KeyHandler::~KeyHandler() {
  delwin(window_);
}

void KeyHandler::timeout(int timeout_ms) {
  timeout_ms_ = timeout_ms;
}

int KeyHandler::getch() {
  wtimeout(window_, timeout_ms_);
  int ch = wgetch(window_);
  return ch;
}

当我使用 g++ 编译时,它说:

$ g++ -c key_handler.cpp
In file included from key_handler.cpp:1:
key_handler.h:12: error: ‘stdscr’ is not a type
key_handler.h:13: error: ‘stdscr’ is not a type
key_handler.cpp:19: error: variable or field ‘wtimeout’ declared void
key_handler.cpp:19: error: expected primary-expression before ‘int’
key_handler.cpp:23: error: ‘int tetris::KeyHandler::wgetch’ is not a static member of ‘class tetris::KeyHandler’
key_handler.cpp:23: error: invalid conversion from ‘WINDOW*’ to ‘int’
key_handler.cpp:23: error: expected ‘,’ or ‘;’ before ‘{’ token
$

其实ncurses库中有timeout和getch。 但我认为它们在不同的命名空间中就可以了。 当我使用其他名称(例如 timeoutff 和 getchff)时,g++ 编译成功。 我认为编译失败是因为函数名重复。 我不想更改我的函数名称。 我应该怎么办?为什么会这样?我不明白。这与 ncurses 库有关,还是即使在使用 STL 时也是 C++ 的普遍问题?

谢谢。

最佳答案

timeout和getch在ncurses.h中被定义为宏

#define timeout(delay)          wtimeout(stdscr,delay)
#define getch()                 wgetch(stdscr)

因此预处理器会在开始实际的 C++ 编译之前替换您的函数。

关于c++使用ncurses库重复函数名称,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16163042/

相关文章:

c - Ncurses 无输出

c - 结构已定义,但编译器声称未定义

c++ - 如何使用 GMP 创建 float 组?

c++ - 从屏幕上的小键盘输入时激活特定的 LineEdit

c++ - 填充字符**

wpf - "Prefix ' .... ' does not map to a namespace",设计师错误?

PHP 扩展命名空间库

C++ 循环 header 依赖

具有相同名称的 PHP CodeIgniter 模型

c - 在 C 中使用 ncurses 的 wrefresh 函数时出现段错误