【问题标题】:Using overloaded operators on pointers在指针上使用重载运算符
【发布时间】:2010-10-29 19:13:38
【问题描述】:

我重载了一个类的

class A {
    std::string operator<<(std::string&);
}

aInst << "This works";
aPointer << "This doesnt work";
aPointer->operator<<("Whereas this works but is useless");

我希望你能帮助我。

海因里希

【问题讨论】:

    标签: c++ operator-overloading


    【解决方案1】:

    您需要先取消引用指针。

    A *ptr = new A();
    (*ptr) << "Something";
    

    唯一的另一种方式是你上面描述的方式

    编辑:Andre 下面的解决方案也是可行的,但就像他说的那样,这可能不是一个好主意。

    【讨论】:

      【解决方案2】:

      首先,为了遵守标准约定,您的operator&lt;&lt; 应该这样声明:

      class A {
          A& operator<<(const std::string&);
      };
      

      现在,从技术上讲,您可以通过实现以下全局函数来实现您想要的部分

      A * operator<< ( A * a, const std::string& s ) { (*a) << s; return a; }
      

      这将允许以下语句:

      string s = "this will be printed."; aPointer << s;
      aPointer << string("this will be printed");
      

      但是,您将无法编写以下内容:

      aPointer << "this will not compile.";
      

      无论如何,编写这样的运算符充其量是令人困惑的。您应该使用更简单的语法

      (*aPointer) << "this will be printed.";
      

      并编写符合既定约定的代码,以允许其他人(以及您自己,在几周内)阅读您的代码。

      【讨论】:

        【解决方案3】:

        你不能那样做。运算符函数仅适用于其中具有枚举或类类型的操作数。

        你毕竟移动了一个指针,而不是一个类。您需要明确表示您想通过首先取消引用指针来转换为类对象。

        【讨论】:

        • @sbi 正确。结构和联合是类。当结构和联合是合适运算符的操作数时,会考虑运算符函数,如使用“类”类键声明的类。
        【解决方案4】:

        通常没有充分的理由这样做,因为语义上运算符

        【讨论】:

        • 不,语义上operator&lt;&lt; 应该返回左侧参数。
        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2011-08-31
        • 1970-01-01
        • 1970-01-01
        • 2021-07-02
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多