我正在尝试创建一个库来简化ncurses用于显示颜色。我这样做是面向对象的,因此将来很容易处理变化。但问题是我无法使用此代码。
#include <ncurses.h>
#include <string.h>
#include <string>
#include <unistd.h>
#include <iostream>
using namespace std;
class ColorWindow {
private:
bool canColor;
WINDOW* container;
int height, width, startx, starty;
public:
ColorWindow() {
if(has_colors()) {
canColor=true;
}
this->height = 20;
this->width = 84;
this->starty = (LINES - height) / 2; /* Calculating for a center placement */
this->startx = (COLS - width) / 2;
}
bool writeStringWithColor(int x, int y, const char* message) {
if(!canColor) {
writeString(3, 5, "Sorry, your term can't show colors.");
return false;
}
init_pair(1, COLOR_RED, COLOR_BLACK);
writeString(0, 10, "aaaaaaaaa");
wattron(getContainer(), COLOR_PAIR(1));
writeString(x, y, message);
wattroff(getContainer(), COLOR_PAIR(1));
}
void writeString(int x, int y, const char* message) {
mvwprintw(getContainer(), x, y, message);
}
WINDOW* createNewContainer() {
this->container = newwin(height, width, starty, startx);
wrefresh(this->container); /* Show that box */
return getContainer();
}
WINDOW* getContainer() {
return this->container;
}
void refreshContainer() {
refresh();
wrefresh(this->container); /* Show that box */
}
};
int main() {
ColorWindow cw = ColorWindow();
initscr(); /* Start curses mode */
cbreak(); /* Line buffering disabled, Pass on
* everything to me */
keypad(stdscr, TRUE);
start_color();
cw.createNewContainer();
bool success = cw.writeStringWithColor(0, 10, "Hello everyone in color!!");
if(!success)
cw.writeString(0, 10, "Write with color failed :(");
cw.refreshContainer();
sleep(2);
endwin();
return 0;
}
先谢谢。
答案 0 :(得分:0)
您的代码中存在一些错误:
您没有初始化canColor
和container
,因此将字段复制到cw
中的main
具有未定义的行为。修正:
ColorWindow() : canColor(false), container(nullptr) {
writeStringWithColor
在结尾处缺少return
语句,也导致main
中的未定义行为。修正:
return true;
在writeStringWithColor
。
在x
的{{1}}来电中,您的y
和mvwprintw
参数已被换掉。修正:
writeString
mvwprintw(getContainer(), y, x, message);
和LINES
仅在初始化ncurses后有效,因此您的COLS
和starty
值是垃圾。通过在startx
中的ncurses初始化代码之后移动cw
的初始化来修复:
main
完整计划:
initscr(); /* Start curses mode */
cbreak(); /* Line buffering disabled, Pass on
* everything to me */
keypad(stdscr, TRUE);
start_color();
ColorWindow cw = ColorWindow();