首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >错误:无法将'std::ostream {aka std::basic_ostream<char>}‘lvalue绑定到'std::basic_ostream<char>&&’

错误:无法将'std::ostream {aka std::basic_ostream<char>}‘lvalue绑定到'std::basic_ostream<char>&&’
EN

Stack Overflow用户
提问于 2022-03-24 10:25:07
回答 1查看 237关注 0票数 0

因此,我最近在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

代码语言:javascript
复制
#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

代码语言:javascript
复制
#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

代码语言:javascript
复制
#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;
}
EN

回答 1

Stack Overflow用户

发布于 2022-03-24 10:29:09

看起来论点的顺序是倒的。见https://learn.microsoft.com/en-us/cpp/standard-library/overloading-the-output-operator-for-your-own-classes。尝试这个声明,以及类似的实现:

代码语言:javascript
复制
friend ostream& operator<<(ostream& os, Test t);
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/71600731

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档