View Code
#include "stdafx.h"
#include <iostream>
#include <windows.h>


#ifndef _CONSOLECOLOR_H_
#define _CONSOLECOLOR_H_

std::ostream& blue(std::ostream &s);
std::ostream& red(std::ostream &s);
std::ostream& green(std::ostream &s);
std::ostream& yellow(std::ostream &s);
std::ostream& white(std::ostream &s);
struct color {
    color(WORD attribute):m_color(attribute){};
    WORD m_color;
};
template <class _Elem, class _Traits>
std::basic_ostream<_Elem,_Traits>& 
      operator<<(std::basic_ostream<_Elem,_Traits>& i, color& c);
      
#include "ConsoleColor.cpp"
#endif

 

ConsoleColor.h

 

ConsoleColor.cpp(该文件一定不要加入工程,放入当前目录即可)

View Code
#include "stdafx.h"
#include "ConsoleColor.h"
inline std::ostream& blue(std::ostream &s)
{
    HANDLE hStdout = GetStdHandle(STD_OUTPUT_HANDLE); 
    SetConsoleTextAttribute(hStdout, FOREGROUND_BLUE
              |FOREGROUND_GREEN|FOREGROUND_INTENSITY);
    return s;
}

inline std::ostream& red(std::ostream &s)
{
    HANDLE hStdout = GetStdHandle(STD_OUTPUT_HANDLE); 
    SetConsoleTextAttribute(hStdout, 
                FOREGROUND_RED|FOREGROUND_INTENSITY);
    return s;
}

inline std::ostream& green(std::ostream &s)
{
    HANDLE hStdout = GetStdHandle(STD_OUTPUT_HANDLE); 
    SetConsoleTextAttribute(hStdout, 
              FOREGROUND_GREEN|FOREGROUND_INTENSITY);
    return s;
}

inline std::ostream& yellow(std::ostream &s)
{
    HANDLE hStdout = GetStdHandle(STD_OUTPUT_HANDLE); 
    SetConsoleTextAttribute(hStdout, 
         FOREGROUND_GREEN|FOREGROUND_RED|FOREGROUND_INTENSITY);
    return s;
}

inline std::ostream& white(std::ostream &s)
{
    HANDLE hStdout = GetStdHandle(STD_OUTPUT_HANDLE); 
    SetConsoleTextAttribute(hStdout, 
       FOREGROUND_RED|FOREGROUND_GREEN|FOREGROUND_BLUE);
    return s;
}

template <class _Elem, class _Traits>
std::basic_ostream<_Elem,_Traits>& 
      operator<<(std::basic_ostream<_Elem,_Traits>& i, color& c)
{
    HANDLE hStdout=GetStdHandle(STD_OUTPUT_HANDLE); 
    SetConsoleTextAttribute(hStdout,c.m_color);
    return i;
}

main.cpp

View Code
#include "stdafx.h"
#include "ConsoleColor.h"
//#include "ConsoleColor.cpp"
void main()
{
    std::cout << green << "This text is written in green" 
          << white << std::endl;
    std::cout << color(FOREGROUND_RED|FOREGROUND_GREEN) 
          << "This text has a really exiting color !" 
          << white << std::endl;
}


关于怎么样使用头文件定义一个模板类参考以下链接:

http://www.codeproject.com/Articles/48575/How-to-define-a-template-class-in-a-h-file-and-imp

 

posted on 2012-05-21 15:50  salomon  阅读(2453)  评论(0编辑  收藏  举报