重载运算符<<私人枚举 [英] Overloading operator<< for a private enum

查看:112
本文介绍了重载运算符<<私人枚举的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的班级有一个私有的enum,其成员用于索引字符串数组,该字符串的输出被写入输出流.

My class has a private enum whose members are being used to index an array of strings, the output of which is written to an output stream.

private:
    enum supportedMessageTypes(CRITICAL = 0, WARNING, INFORMATION);
    string messages[3];

//meanwhile, inside the constructor,
messages[3] = {"Critical error message", 
               "Warning message", 
               "Information message"};

由于我将在代码中大量使用枚举值,因此我希望能够重载operator<<来执行枚举值的查找,并将其与数组中的相应字符串匹配,并以以下方式返回:

Since I'm going to be using the enum values around my code a lot, I'd like to be able to overload operator<< to perform a lookup of the enum value, match it to the corresponding string in the array, and return that in the following manner:

cout << CRITICAL << ": " << messageText << std::endl;

我的问题是supportedMessageTypes是私有的,而operator<<的重载应作为非成员函数来完成.我知道我可以为我的类定义一个friend函数,该函数将operator<<重载,但是我根本不愿意以这种方式破坏封装,并且想知道是否有人知道一种不用friend功能还是将supportedMessageTypes公开?

The problem I have is that supportedMessageTypes is private while overloading of operator<< should be done as a non-member function. I know I can define a friend function that overloads operator<< for my class, but I'm simply not comfortable with breaking encapsulation in that way, and was wondering if anyone knew of a way to overload operator<< without using friend functions or making supportedMessageTypes public?

推荐答案

这是不可能的.您要接受类型为supportedMessageTypes的参数,因此该参数必须可见.没办法解决.

This isn't possible. You want to accept an argument of type supportedMessageTypes, so it must be visible. There's no way around it.

此外,friend函数在这里也不错.这是旨在实现友谊的一种方案.

Also, a friend function wouldn't be bad here; this is one of the intented scenarios for friendship.

这篇关于重载运算符&lt;&lt;私人枚举的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆