我必须重载哪个运算符?

发布于 2024-12-05 02:48:57 字数 105 浏览 0 评论 0原文

如果我想像这样使用某物,我必须重载哪个运算符?

MyClass C;

cout<< C;

我的类的输出将是字符串。

Which operator do I have to overload if I want to use sth like this?

MyClass C;

cout<< C;

The output of my class would be string.

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

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

发布评论

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

评论(3

微暖i 2024-12-12 02:48:57

如果您必须将 operator<< 重载为:

std::ostream& operator<<(std::ostream& out, const MyClass & obj)
{
   //use out to print members of obj, or whatever you want to print
   return out;
}

如果此函数需要访问 MyClass 的私有成员,那么您必须将其设为 friendMyClass 的 code>,或者,您可以将工作委托给类的某些公共函数。

例如,假设您有一个点类定义为:

struct point
{
    double x;
    double y;
    double z;
};

然后您可以将 operator<< 重载为:

std::ostream& operator<<(std::ostream& out, const point & pt)
{
   out << "{" << pt.x <<"," << pt.y <<"," << pt.z << "}";
   return out;
}

并且您可以将其用作:

point p1 = {10,20,30};
std::cout << p1 << std::endl;

输出:

{10,20,30}

在线演示: http://ideone.com/zjcYd

希望有所帮助。

if you've to overload operator<< as:

std::ostream& operator<<(std::ostream& out, const MyClass & obj)
{
   //use out to print members of obj, or whatever you want to print
   return out;
}

If this function needs to access private members of MyClass, then you've to make it friend of MyClass, or alternatively, you can delegate the work to some public function of the class.

For example, suppose you've a point class defined as:

struct point
{
    double x;
    double y;
    double z;
};

Then you can overload operator<< as:

std::ostream& operator<<(std::ostream& out, const point & pt)
{
   out << "{" << pt.x <<"," << pt.y <<"," << pt.z << "}";
   return out;
}

And you can use it as:

point p1 = {10,20,30};
std::cout << p1 << std::endl;

Output:

{10,20,30}

Online demo : http://ideone.com/zjcYd

Hope that helps.

梦里梦着梦中梦 2024-12-12 02:48:57

流运算符:<<

您应该将其声明为您班级的朋友:

class MyClass
{
    //class declaration
    //....
    friend std::ostream& operator<<(std::ostream& out, const MyClass& mc);
}

std::ostream& operator<<(std::ostream& out, const MyClass& mc)
{
    //logic here
}

The stream operator: <<

You should declare it as a friend of your class:

class MyClass
{
    //class declaration
    //....
    friend std::ostream& operator<<(std::ostream& out, const MyClass& mc);
}

std::ostream& operator<<(std::ostream& out, const MyClass& mc)
{
    //logic here
}
谁人与我共长歌 2024-12-12 02:48:57

您应该将 operator<< 实现为自由函数。

You should implement operator<< as a free function.

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