C ++相当于java.toString? [英] C++ equivalent of java.toString?

查看:114
本文介绍了C ++相当于java.toString?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想控制写入流的内容,即 cout ,用于自定义类的对象。在C ++中是可能的吗?在Java中,您可以覆盖 toString()方法,用于类似目的。

解决方案

在C ++中,您可以为 ostream 和您的自定义类重载 operator
$ b

  class A {
public:
int i;
};

std :: ostream& operator<<<(std :: ostream& strm,const A& a){
return strm< A(

  A x = ...; 
std :: cout<< x<< std :: endl;

如果您的运算符<< 打印出 A 的内部,真正需要访问其私有和受保护的成员,你也可以将它声明为一个朋友函数:

  class A {
private:
friend std :: ostream& operator<<(std :: ostream& const A&);
int j;
};

std :: ostream& operator<<<(std :: ostream& strm,const A& a){
return strm< A(< a.j<<);
}


I'd like to control what is written to a stream, i.e. cout, for an object of a custom class. Is that possible in C++? In Java you could override the toString() method for similar purpose.

解决方案

In C++ you can overload operator<< for ostream and your custom class:

class A {
public:
  int i;
};

std::ostream& operator<<(std::ostream &strm, const A &a) {
  return strm << "A(" << a.i << ")";
}

This way you can output instances of your class on streams:

A x = ...;
std::cout << x << std::endl;

In case your operator<< wants to print out internals of class A and really needs access to its private and protected members you could also declare it as a friend function:

class A {
private:
  friend std::ostream& operator<<(std::ostream&, const A&);
  int j;
};

std::ostream& operator<<(std::ostream &strm, const A &a) {
  return strm << "A(" << a.j << ")";
}

这篇关于C ++相当于java.toString?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆