因此,我最近在c++大学期间批准了OOP,我发现自己遇到了一些问题。我尝试超载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;。我读过这个错误,但不能把它加起来,我应该做什么,我在做什么错误?
Test.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
#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
#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;
}发布于 2022-03-24 10:29:09
看起来论点的顺序是倒的。见https://learn.microsoft.com/en-us/cpp/standard-library/overloading-the-output-operator-for-your-own-classes。尝试这个声明,以及类似的实现:
friend ostream& operator<<(ostream& os, Test t);https://stackoverflow.com/questions/71600731
复制相似问题