让编译器感知 <<为特定类定义

发布于 2024-09-01 14:31:57 字数 892 浏览 2 评论 0 原文

我用这个问题编辑了我的帖子,但没有得到答案。

我超载了<<对于类,Score(在score.h 中定义),位于score.cpp 中。

ostream& operator<< (ostream & os, const Score & right)
{
 os << right.getPoints() << " " << right.scoreGetName();
 return os;
}

getPoints 获取一个 int 属性,getName 一个 string 一个)

我在 main 中进行测试时收到此编译错误(),包含在 main.cpp 中

binary '<<' : no operator found which takes a right-hand operand of type 'Score' (or there is no acceptable conversion)

编译器为何不“识别”该重载有效? (包含是正确的)

感谢您的宝贵时间。

编辑:

根据要求,导致错误的代码:

cout << ":::::\n" << jogador.getScore() << endl;

jogador 是一个 Player 对象,其中包含一个 Score 对象。 getScore 返回该属性。

I edited a post of mine with this question, yet got no answers.

I overloaded << for a class, Score (defined in score.h), in score.cpp.

ostream& operator<< (ostream & os, const Score & right)
{
 os << right.getPoints() << " " << right.scoreGetName();
 return os;
}

(getPoints fetches an int attribute, getName a string one)

I get this compiling error for a test in main(), contained in main.cpp

binary '<<' : no operator found which takes a right-hand operand of type 'Score' (or there is no acceptable conversion)

How come the compiler doesn't 'recognize' that overload as valid? (includes are proper)

Thanks for your time.

EDIT:

As requested, code causing the error:

cout << ":::::\n" << jogador.getScore() << endl;

jogador is a Player object, which contains a Score one. getScore returns that attribute.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

一个人的夜不怕黑 2024-09-08 14:31:57

也许您没有在 score.h 中声明您的 operator<< ?它通常应包含类似以下内容:

ostream& operator<< (ostream & os, const Score & right);

编辑:更准确地说,应该是:

std::ostream &operator<<(std::ostream &os, const Score &right);

您绝对不应该在标头中包含 using namespace std; ,因此您需要 std:: 才能正常工作。

Perhaps you didn't declare your operator<< in score.h? It should normally contain something like:

ostream& operator<< (ostream & os, const Score & right);

Edit: More accurately, that should be:

std::ostream &operator<<(std::ostream &os, const Score &right);

You definitely should not have a using namespace std; in a header, so you need the std:: for it to work correctly.

舂唻埖巳落 2024-09-08 14:31:57

尝试将 operator<< 声明为类中的 friend 函数:

struct Score
{
  friend ostream& operator<<(ostream& output, const Score& right);
};

这将使您的 Score 结构很好地适合打印语句

Score my_score;
cout << my_score << endl;

:如有疑问,请查看C++ 常见问题解答

Try declaring operator<< as a friend function in your class:

struct Score
{
  friend ostream& operator<<(ostream& output, const Score& right);
};

This will allow your Score structure to fit nicely into printing statements:

Score my_score;
cout << my_score << endl;

When in doubt, check the C++ FAQ.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文