重载运算符<<对于枚举类

时间:2016-07-27 15:50:32

标签: c++ enums operator-overloading

尝试在一段时间后重新编写代码,但是我遇到了令我难过的链接器错误。我正试图重载<<枚举类的运算符。这是“Enum.h”:

#ifndef ENUM_H
#define ENUM_H

#include <iostream>
#include <ostream>

enum class Color { Unknown = 0, Red, Blue, Green, Yellow, White, Multicolor };
std::ostream& operator<<(std::ostream& out, const Color& obj);

#endif

这是“Enum.cpp”:

#include "stdafx.h"

std::ostream& operator<<(std::ostream& out, const Color& obj) {
    switch (obj){
    case(Color::Red) : out << "red"; break;
    case(Color::Blue) : out << "blue"; break;
    case(Color::Green) : out << "green"; break;
    case(Color::Yellow) : out << "yellow"; break;
    case(Color::White) : out << "white"; break;
    case(Color::Multicolor) : out << "multicolor"; break;
    default: out << "of unknown color"; break;
    }

    return out;
}

stdafx.h包含“Enum.h”,iostream,ostream,主文件定义了一个颜色并试图将它传递给std :: cout,如下所示:

#include "stdafx.h"

using namespace System;

int main(array<System::String ^> ^args)
{
    Color c = Color::Red;
    std::cout << c;

    return 0;
}

但是,我收到以下编译器错误:

error LNK2019: unresolved external symbol "class std::basic_ostream<char,struct std::char_traits<char> > & __cdecl operator<<(class std::basic_ostream<char,struct std::char_traits<char> > &,enum Color const &)" (??6@$$FYAAAV?$basic_ostream@DU?$char_traits@D@std@@@std@@AAV01@ABW4Color@@@Z) ...

0 个答案:

没有答案