【问题标题】:Getting string from class object [duplicate]从类对象中获取字符串[重复]
【发布时间】:2019-04-30 14:19:27
【问题描述】:

我创建了一个基于 bitset 的字符串类,它有自己的 getstring 函数。我怎样才能做到这一点,以便每当我调用对象时,它都会调用该函数然后返回结果。我希望它像实际的字符串类一样,您可以在其中执行 std::cout

提前致谢

【问题讨论】:

  • 你应该重载operator<<
  • 重载运算符 const char*() 也可以工作
  • 如何“调用”一个对象?

标签: c++ string class bitset


【解决方案1】:

不看你的代码很难回答这个问题,但听起来你想实现这样的东西

class Foo(){
  public:
  std::string GetString(){return myString;}
  std::string SetString(std::string str){myString = str;}

  friend std::ostream& operator<<(std::ostream& os, const Foo& foo)
  {
    return os << "My String Is:" << GetString() << "\n";
  }
  private:
  std::string myString;
};

【讨论】:

  • 对帖子进行了编辑,将 bar 重命名为 myString
  • 那就是 foo.GetString() 那么,这就是将 foo 作为参数传递的目的,不是吗?我也怀疑class Foo() { 会编译吗?
猜你喜欢
  • 1970-01-01
  • 2013-07-01
  • 1970-01-01
  • 2021-05-24
  • 1970-01-01
  • 2014-03-25
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多