【问题标题】:Return value for a << operator function of a custom string class in C++C++ 中自定义字符串类的 << 运算符函数的返回值
【发布时间】:2010-11-18 00:55:49
【问题描述】:

我正在尝试创建自己的 std::string 包装器以扩展其功能。 但是我在声明

我的自定义字符串类:

class MyCustomString : 私有 std::string
{
民众:
  标准::字符串数据;
  MyCustomString() { data.assign(""); }
  MyCustomString(char *value) { data.assign(value); }
  无效分配(字符*值){ data.assign(值); }
  // ...其他有用的功能
  std::string & operator data; }
};

主程序:

int main()
{
  MyCustomString mystring("Hello");
  std::cout  &' 的转换存在,但不可访问

  返回0;
}

我希望 cout 将类视为 std::string,这样我就不需要执行以下操作:

std::cout 

任何形式的帮助都将不胜感激!

谢谢。

仅供参考:我的 IDE 是 Microsoft Visual C++ 2008 Express Edition。

【问题讨论】:

  • 我在这里添加其他答案,您需要独立(全局函数)的原因是因为第一个参数的类型需要是 std::string 或您想要的任何类型在&lt;&lt; 运算符之前。
  • ... 这是在不修改实际 std::string 类的情况下提供此类运算符的唯一方法。

标签: c++ operator-overloading


【解决方案1】:

如果您查看所有流运算符的声明方式,它们的形式如下:

ostream& operator<<(ostream& out, const someType& val );

本质上,您希望您的重载函数实际执行输出操作,然后返回新更新的流操作符。我建议执行以下操作,请注意这是一个全局函数,而不是您班级的成员:

ostream& operator<< (ostream& out, const MyCustomString& str )
{
    return out << str.data;
}

请注意,如果您的“数据”对象是私有的,基本 OOP 说它可能应该是私有的,那么您可以在内部将上述运算符声明为“朋友”函数。这将允许它访问私有数据变量。

【讨论】:

    【解决方案2】:

    你需要一个独立的函数(你班上的朋友,如果你把你的data设为私有,你可能应该这样做!)

    inline std::ostream & operator<<(std::ostream &o, const MyCustomString&& d)
    {
        return o << d.data;
    }
    

    【讨论】:

      【解决方案3】:

      这不是您重载 std::cout << lol << lol2)。

      ostream& operator << (ostream& os, const MyCustomString& s);
      

      然后这样做:

      ostream& operator << (ostream& os, const MyCustomString& s)
      {
         return os << s.data;
      }
      

      【讨论】:

        【解决方案4】:

        首先,您似乎对 MyCustomString 的定义有疑问。它从std::string 私下继承,并包含std::string 本身的一个实例。我会删除其中一个。

        假设您正在实现一个新的字符串类并且您希望能够使用std::cout 输出它,您将需要一个转换运算符来返回std::cout 期望的字符串数据:

        operator const char *()
        {
            return this->data.c_str();
        }
        

        【讨论】:

        • 不自​​动衰减为 C 字符串是使用(正确)字符串的最基本动机之一。为 C 字符串提供隐式转换运算符可以解决此问题。
        • 同意,它应该是显式的或类似于 std::string (使用 .c_str()),但是直到 C++11 之前,显式运算符才存在于此回答
        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2015-05-09
        • 2021-02-20
        • 2023-03-10
        • 1970-01-01
        • 2016-08-26
        相关资源
        最近更新 更多