简体   繁体   English

不能为我自己的类重载运算符 <<

[英]Can`t overload the operator << for a my own class

I am trying to reduce code redundancy using the overload of an output operator to a stream instead of print functions.我试图使用输出运算符重载到流而不是打印函数来减少代码冗余。

//***.h
class MainWind : public QWidget
{
    Q_OBJECT

public:
    explicit MainWind(QWidget *parent = nullptr);
    ~MainWind();
    MainWind *operator<<(const QString &str);
private:
    Ui::MainWind *ui;
};

//***.cpp
MainWind *MainWind::operator<<(const QString &str)
{
    ui->serverConsole->insertPlainText(str);
    return this;
}

At this moment everything compiles successfully.此时一切都编译成功。

But when I try to use:但是当我尝试使用时:

//other.cpp
MainWind *mainWind  = new MainWind;
mainWind << QString("str");

I got this error:我收到此错误:

ServerSocket.cpp:39: error: invalid operands to binary expression ('MainWind *' and 'QString') qstring.h:1410: candidate function not viable: no known conversion from >'MainWind *' to 'QDataStream &' for 1st argument ServerSocket.cpp:39: 错误: 二进制表达式的无效操作数 ('MainWind *' 和 'QString') qstring.h:1410: 候选函数不可行:没有已知的从 >'MainWind *' 到 'QDataStream &' 的转换为 1st争论

... ...

And there are a lot of candidates for this position)而且这个职位的候选人很多)

Or或者

//other.cpp
MainWind *mainWind  = new MainWind;
mainWind <<"str";

I got this error:我收到此错误:

ServerSocket.cpp:39: error: invalid operands to binary expression ('MainWind *' and 'const char [4]') ServerSocket.cpp:39: error: invalid operands of types 'MainWind*' and 'const char [4]' to binary 'operator<<' CurrentSession::inst().mainWind() << "str"; ServerSocket.cpp:39: 错误: 二进制表达式的无效操作数 ('MainWind *' 和 'const char [4]') ServerSocket.cpp:39: 错误: 'MainWind*' 和 'const char [4] 类型的操作数无效' 到二进制 'operator<<' CurrentSession::inst().mainWind() << "str";

 ^

What could be the problem?可能是什么问题呢?

ADDITION TO THIS QUESTION:这个问题的补充:

Attempt to use:尝试使用:

//*.h
friend MainWind *operator<<(MainWind *out,QString &str);

//***.cpp
MainWind * operator<<(MainWind *out, QString &str)
{
    out->ui->serverConsole->insertPlainText(str);
    return out;
}

Compilation of previous code is successful.之前的代码编译成功。

According to the idea, if the first operand could not be a pointer, this code would not compile...根据这个想法,如果第一个操作数不能是指针,这段代码就不会编译......

But when using this:但是当使用这个时:

//other.cpp
MainWind *mW = new MainWind;
mW << "str";

Compilation go to error:编译出错:

ServerSocket.cpp:37: error: invalid operands of types 'MainWind*' and 'const char [4]' to binary 'operator<<' mW << "str"; ServerSocket.cpp:37: 错误:'MainWind*' 和 'const char [4]' 类型的无效操作数到二进制 'operator<<' mW << "str";

 ^

You need to use *mainWind << QString("str");您需要使用*mainWind << QString("str"); . . The LHS has to be an object, not a pointer. LHS 必须是一个对象,而不是一个指针。

While at it, I strongly recommend changing the operator<< function to return a reference to the object, not a pointer.在此期间,我强烈建议更改operator<<函数以返回对对象的引用,而不是指针。

MainWind& operator<<(const QString &str);

and the implementation to和实施

MainWind& MainWind::operator<<(const QString &str)
{
    ui->serverConsole->insertPlainText(str);
    return *this;
}

That will allow you to chain the operator.这将允许您链接运算符。

*mainWind << QString("str") << QString("Second string");

You overloaded << on MainWnd not MainWnd* .您在MainWnd上重载了<< MainWnd不是MainWnd*

*mainWind << QString("str");

Also you want QString const&你还想要QString const&

//other.cpp MainWind *mainWind = new MainWind; mainWind <<"str";

The reason is that mainWind << "str" looks for an operator<<() that accepts two arguments, the first of which is a MainWind * .原因是mainWind << "str"查找接受两个参数的operator<<() ,其中第一个是MainWind *

Whereas, you have defined a MainWind::operator<<() which is called with the first argument a MainWind & .而您已经定义了一个MainWind::operator<<() ,它使用第一个参数MainWind &调用。 There is no direct conversion from a MainWind * to a MainWind & (or to a MainWind ).没有从MainWind *MainWind & (或到MainWind )的直接转换。 Hence the error message.因此出现错误消息。

One way to get the code to compile is to change mainWind <<"str" to *mainWind << "str" .编译代码的一种方法是将mainWind <<"str"更改为*mainWind << "str" The * dereferences the pointer, and produces a reference, which is what your operator<<() expects. *取消引用指针,并生成一个引用,这是您的operator<<()期望的。

The catch is then that问题是

*mainWind << "str" << "another str";

will not compile, since it is equivalent to不会编译,因为它等价于

(*mainWind).operator<<("str") << "another str";

where (*mainWind).operator<<("str") returns a MainWind * .其中(*mainWind).operator<<("str")返回MainWind * This causes the same problem (again) when trying to stream "another str" .当尝试流式传输"another str"时,这会导致同样的问题(再次)。

The real fix is to change operator<<() so it returns a reference真正的解决方法是改变operator<<()所以它返回一个引用

//  within the class definition of MainWind

MainWind &operator<<(const QString &str);

// definition of the operator<<()

MainWind &MainWind::operator<<(const QString &str)
{
    ui->serverConsole->insertPlainText(str);
    return *this;
}

and change the calling code to either并将调用代码更改为

//other.cpp version 2

MainWind *mainWind  = new MainWind;
*mainWind <<"str";

// this will work too

*mainWind << "str" << "another str";  

//   note reliance on cleaning up mainWind to avoid a memory leak

delete mainWind;   

There is no other fix that would allow you to use mainWind << "str" since overloading non-member operator<<() is only permitted on class or enumerated types, not on pointers.没有其他修复可以让您使用mainWind << "str"因为重载非成员operator<<()只允许在类或枚举类型上,而不是在指针上。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 C ++-为学校建立我自己的String类,无法正确重载&lt;运算符 - C++ - Building my own String class for school, can't overload < operator correctly 不能重载“ &lt;&lt;”运算符 - Can't overload “<<” operator 试图重载和运算符“+”但无法正确定义 class 构造函数 - Trying to overload the sum operator “+” but can't defind the class constructor right 如何为包含我自己的类对象的向量重载运算符“ []” - How do i overload operator “[]” for vector containing my own class objects 我不能重载输入运算符来输入字符数组(C风格的字符串),即我的类的成员变量吗? - Can't I overload the input operator to input an array of characters (C-style string), that is a member variable of my class? 为什么我在这个 C++ 类中的重载 operator+ 不需要实现为 operator-? - Why my overload operator+ in this c++ class doesn't need to be implemented as operator-? 带有自己的类和 std::string_view 的“operator==”的不明确重载 - Ambiguous overload for 'operator==' with own class and std::string_view 我可以在这里重载&lt;&lt;操作符吗? - Can I overload the << operator in a base class here? 如何重载抽象类的运算符? - How can I overload an operator for an abstract class? 重载=运算符,无法使其正常工作 - Overload =operator, can't get it to work
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM