在指针上使用重载运算符

Eri*_*rik 13 c++ operator-overloading

我重载了一个类的<<运算符.如果我想在指针上使用它,我如何重载运算符,如下所示?

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

aInst << "This works";
aPointer << "This doesnt work";
aPointer->operator<<("Whereas this works but is useless");
Run Code Online (Sandbox Code Playgroud)

我希望你能帮助我.

海因里希

Mik*_*ley 23

您需要先取消引用指针.

A *ptr = new A();
(*ptr) << "Something";
Run Code Online (Sandbox Code Playgroud)

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

编辑:以下安德烈的解决方案也是可行的,但他说这可能不是一个好主意.


And*_*ron 12

首先,要坚持使用标准约定,您operator<<应该像这样声明:

class A {
    A& operator<<(const std::string&);
};
Run Code Online (Sandbox Code Playgroud)

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

A * operator<< ( A * a, const std::string& s ) { (*a) << s; return a; }
Run Code Online (Sandbox Code Playgroud)

这将允许诸如以下的陈述:

string s = "this will be printed."; aPointer << s;
aPointer << string("this will be printed");
Run Code Online (Sandbox Code Playgroud)

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

aPointer << "this will not compile.";
Run Code Online (Sandbox Code Playgroud)

无论如何,写这样一个运营商至多让人感到困惑.你应该使用更简单的语法

(*aPointer) << "this will be printed.";
Run Code Online (Sandbox Code Playgroud)

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