小编use*_*308的帖子

将 std 字符串访问器与 ostream 运算符 << 一起使用

如果我创建一个类:

// First Example
#include <iostream>
#include <string>

class my_class {
  std::string str;
public:
  my_class(const char* s = "") : str(s) {}

  operator const char* () const { return str.data(); } // accessor
};

my_class mc1{"abc"};
std::cout << mc1; // Calls the char* accessor and successfully writes "abc" to screen output.
Run Code Online (Sandbox Code Playgroud)

如果我这样修改类:

// Second Example
class my_class {
  std::string str;
public:
  my_class(const char* s = "") : str(s) {}

  operator std::string () const { return str; } // accessor
}; …
Run Code Online (Sandbox Code Playgroud)

c++ string iostream overloading accessor

2
推荐指数
1
解决办法
144
查看次数

标签 统计

accessor ×1

c++ ×1

iostream ×1

overloading ×1

string ×1