运算符<<<需要const;产生头痛 [英] Operator overload of << needs const; produces headache

查看:92
本文介绍了运算符<<<需要const;产生头痛的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试重载operator <<,但是它总是需要成为const函数.但是,我想更改此重载函数内的值.我该怎么做?

I am trying to overload operator <<, but it always need to be a const function. However, I want to change values inside this overloaded function. How do I do this?

EDIT1 :代码存根如下:

class Check

{   
public:
    void operator << (boost::any)
    {
        // checks weather the given is hresult,string(filename) or int(line no) 
        // and dump them into the exception object, 
        // There by hresult will initiate the object and int will throw the object.
        // so the input order must be like below
    }
private:
    Exception exception;
};

用法

Check   check;
check << file->open << __FILE__ << __LINE__ ;

EDIT2 :这是给曾经说过语法不好实现的人的 我不是一个很好的专家.程序员.我只是想为例外情况提供快速解决方案.我的动机是它不应该花费更多的时间,它应该易于键入.因为我的同事必须使用此异常类.我试图找到解决方案,答案为<<运算符重载.例如,请考虑以下示例

This is for who ever said that the syntax is not good to implement I am not a well exp. programmer. I just tried to make a quick solution for exception. My motive is it shouldn't consume more time, it should be easy to type. Because my colleagues have to use this exception class. I tried to find a solution for that, and the answer came as << operator overloading. For example consider the below sample

1)我的方法

#define INFO __LINE__ << __FILE__
c++
RunAndCheck runAndCheck;

try
{
    runAndCheck << checkVersion() << INFO;
    runAndCheck << file->Open() << INFO;
    runAndCheck << file->rename() << INFO;
}
catch(...)
{
}

2)传统方法

#define INFO __FILE__,__LINE__
try
{
    runAndCheck.check(checkVersion(),INFO);
    runAndCheck.check(file->Open(),INFO);
    runAndCheck.check(file->rename(),INFO);
}
catch(...)
{
}

可能在此存根中或多或少都相同,但请考虑使用win32API的情况.在那里,必须检查每个呼叫是否有异常.在那种情况下,我发现<<重载很容易输入.这样我就做了这样的语法

May be in this stub it will be more or less same, but consider a situation where win32API used. There every call must be checked for exception. In that case, I found << overloading is easy to type. So that I made such a syntax

推荐答案

那么您可能做错了什么.张贴代码的相关部分,以及关于您想做什么的更好的摘要,您将获得更多帮助.

You're likely doing something wrong then. Post the relevant bits of your code, along with a better summary of what your trying to do, and you'll get more help.

话虽如此,如果您需要修改const对象中的某些数据,则可以做几件事:

That being said, if you need to modify some data in a const object, there are a couple things you can do:

  1. 声明要修改的成员mutable.
  2. 使用const_cast<...>(...)从传入的对象中删除const修饰符.
  1. Declare the member you want to modify mutable.
  2. Use const_cast<...>(...) to remove the const modifier from the passed in object.

但是很可能您正在尝试以错误的方式做某事.

But most likely you're trying to do something the wrong way.

这篇关于运算符&lt;&lt;&lt;需要const;产生头痛的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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