簡體   English   中英

使用替代cout時“使用適當的位掩碼進行廣播”

[英]“cast with the appropriate bitmask” while using alternative cout

因此,我決定制作一個控制台類來替代std::cout << stream << std::endl例程。 這是我的代碼:

class Console {
 public:
    Console() {
        this->console = GetStdHandle(STD_OUTPUT_HANDLE);
        this->current_color = 7;
    }
    void color(int k) {
        this->current_color = k;
        SetConsoleTextAttribute(this->console, this->current_color);
    }
    void remove() {
        FreeConsole();
    }
    void print(std::string s) {
        std::cout << s;
    }
    void log(std::string s) {
        this->color(7);
        std::cout << s << std::endl;
        this->color(this->current_color);
    }
    void error(std::string s) {
        this->color(12);
        std::cout << s << std::endl;
        this->color(this->current_color);
    }
 private:
    HANDLE console;
    int current_color;
};

將控制台初始化為Console console; ,例如,我使用console.log("String " + n) ,其中n是一個無符號的short。 代碼可以正常編譯,但是出現了以下內容: 在此處輸入圖片說明 這是什么,我該如何解決?

您的程序包含未定義的行為。

console.log("String " + n) (其中n是整數類型)的解釋如下:

const char* tmp_ptr1 = "String ";
const char* tmp_ptr2 = tmp_ptr1 + n;
console.log(std::string(tmp_ptr2));

如果n > 7n < 0則上述代碼執行越界訪問。 在您的情況下,這種訪問恰好是從鏈接到程序數據部分的字符串文字中選取其他(子)字符串,然后在屏幕上看到它。 理論上,任何其他事情都可能發生。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM