【问题标题】:Insertion Overload with String to Object使用字符串到对象的插入重载
【发布时间】:2020-07-07 05:03:51
【问题描述】:

这里是 C++ 新手。我有我正在做的项目 要求我像这样重载插入运算符:

someObject << “stringOne” << “stringTwo” << stringThree <<;

这行代码的想法本质上是将一些字符串添加到一个数组中 ' 成立。

我知道插入重载的原型是这样的,但是我不确定如何定义实际的函数,所以它就像我上面提到的那样工作。

friend std::ostream& operator<<(ostream& os, const someClass& classObj);

我在网上看到的所有示例总是将“ostream&标识符”作为左操作数,将对象作为右操作数,就像这样 'os

【问题讨论】:

    标签: c++ operator-overloading insertion


    【解决方案1】:

    您只需将operator&lt;&lt; 设为成员函数即可获得所需的语法:

    someClass& operator<<(std::string str) {
        // add the string to this
        return *this;
    }
    

    你可以这样做:

    someObject << "hello" << "world";
    

    您可以在右侧为您想要的任何其他类型添加额外的重载。

    这是demo

    【讨论】:

      【解决方案2】:

      我认为你需要为你的类重载插入操作符。

      #include <iostream>
      #include <string>
      #include <vector>
      
      using namespace std;
      
      class A {
      public:
      
        A & operator <<(const std::string & s) {
          v.push_back(s);
          return *this;
        }
      
        void print() const {
          for (auto & s: v) {
            cout << "element:" << s << endl;
          }
        }
      
      private:
        vector<string> v;
      };
      
      int main() {
        A a;
        string s = "string object";
      
        a << "test" << "string" << s;
      
        a.print();
      
        return 0;
      }
      

      【讨论】:

        【解决方案3】:

        该技术称为“链接”,您看到的示例是不言自明的。链式运算符作用于对对象和参数的引用,并返回对对象的引用。

        DataList &  operator<<(DataList &out, const Data &arg)
        {
             // insert arg into out
             return out; 
        }
        

        在这种情况下

        someObject << “stringOne” << “stringTwo” << stringThree;
        

        就像工作

        ((someObject << “stringOne”) << “stringTwo”) << stringThree;
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2012-09-30
          • 2015-09-22
          • 1970-01-01
          • 2012-05-10
          • 1970-01-01
          • 2019-02-13
          • 2015-09-14
          • 1970-01-01
          相关资源
          最近更新 更多