[英]error: cannot bind 'std::ostream {aka std::basic_ostream<char>}' lvalue to 'std::basic_ostream<char>&&'
So, I have recently approched OOP in c++ through university and I found myself with a few problems.所以,我最近通过大学在 c++ 中获得了 OOP,我发现自己遇到了一些问题。 I gave a shot at overloading the ostream operator <<
and found myself with some problems to solve.我试过重载ostream operator <<
并发现自己有一些问题需要解决。 First was that doing the overloading as ostream& operator<<(ostream& outs, const Test&);
首先是将重载作为ostream& operator<<(ostream& outs, const Test&);
carries a problem described as \src\Test.h:15:48: error: 'std::ostream& test::Test::operator<<(std::ostream&, const test::Test&)' must take exactly one argument ostream& operator<<(ostream& outs, const Test&);
带有描述为\src\Test.h:15:48: error: 'std::ostream& test::Test::operator<<(std::ostream&, const test::Test&)' must take exactly one argument ostream& operator<<(ostream& outs, const Test&);
, so, just like I did with the operator ==
removed the second argument. ,所以,就像我对operator ==
所做的那样,删除了第二个参数。 But once i Try to build the following code i get the error: \src\main.cpp:9:10: error: cannot bind 'std::ostream {aka std::basic_ostream<char>}' lvalue to 'std::basic_ostream<char>&&' cout << t;
但是一旦我尝试构建以下代码,我就会收到错误: \src\main.cpp:9:10: error: cannot bind 'std::ostream {aka std::basic_ostream<char>}' lvalue to 'std::basic_ostream<char>&&' cout << t;
. . I read this error but can't comprhend it, what should I do and what is the mistake I'm doing?我读到这个错误但无法理解它,我应该怎么做以及我在做什么错误?
Test.h测试.h
#include <iostream>
#include <cstring>
using namespace std;
#ifndef SRC_TEST_H_BECCIO
#define SRC_TEST_H_BECCIO
namespace test {
class Test {
private:
string mStr;
public:
Test(string str);
string getString(){return this->mStr;};
ostream& operator<<(ostream& outs);
};
} /* namespace test */
#endif /* SRC_TEST_H_BECCIO */
Test.cpp测试.cpp
#include "Test.h"
namespace test {
Test::Test(string str) {
this->mStr=str;
}
ostream& Test::operator<<(ostream& outs){
outs << this->getString()<<endl;
return outs;
}
} /* namespace test */
main.cpp主.cpp
#include <iostream>
#include "Test.h"
using namespace std;
using namespace test;
int main() {
Test t("let's hope this goes well");
cout << t;
return 0;
}
It looks like the order of the arguments is backwards.看起来 arguments 的顺序是倒过来的。 See https://learn.microsoft.com/en-us/cpp/standard-library/overloading-the-output-operator-for-your-own-classes .请参阅https://learn.microsoft.com/en-us/cpp/standard-library/overloading-the-output-operator-for-your-own-classes 。 Try this declaration, and a similar implementation:试试这个声明和类似的实现:
friend ostream& operator<<(ostream& os, Test t);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.