提问人:Beccio-san 提问时间:3/24/2022 最后编辑:Solomon UckoBeccio-san 更新时间:3/24/2022 访问量:445
错误:无法将“std::ostream {aka std::basic_ostream<char>}”左值绑定到“std::basic_ostream<char>&&”
error: cannot bind 'std::ostream {aka std::basic_ostream<char>}' lvalue to 'std::basic_ostream<char>&&'
问:
所以,我最近在大学里学习了 c++ 的 OOP,我发现自己遇到了一些问题。
我尝试了超载,发现自己有一些问题需要解决。
首先,执行重载 as 会带来一个被描述为 的问题,所以,就像我删除的第二个参数一样。但是一旦我尝试构建以下代码,就会出现错误:.
我读了这个错误,但无法理解它,我该怎么办,我犯了什么错误?ostream operator <<
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&);
operator ==
\src\main.cpp:9:10: error: cannot bind 'std::ostream {aka std::basic_ostream<char>}' lvalue to 'std::basic_ostream<char>&&' cout << t;
测试.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 */
测试 .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 */
主 .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;
}
答:
看起来参数的顺序是倒退的。请参见 https://learn.microsoft.com/en-us/cpp/standard-library/overloading-the-output-operator-for-your-own-classes。 请尝试此声明,以及类似的实现:
friend ostream& operator<<(ostream& os, Test t);
评论
friend
const
Test
getString
mStr
Test const
Test const&
friend
评论