简体   繁体   English

了解代码

[英]understanding the code

Can some one explain me this code there is a class StringStream . 可以给我解释一下这段代码StringStream有一个StringStream类。 What i don't get is StringStream& write(char*) . 我没有得到的是StringStream& write(char*) and if in cpp file there is 如果在cpp文件中

StringStream& StringStream::write(char* text)
{
   //what values can i return??
   //can i return address of character text is currently pointing to?
}

You'd return *this - ie a reference to the current object. 您将返回*this this-即对当前对象的引用。 (Well, you can return any non-local StringStream , but I guess the purpose is the one I stated) (好吧,您可以返回任何非本地的StringStream ,但我想目的是我所说的)

This technique is usually used for method chaining - ie doing something like: 此技术通常用于方法链接-即执行以下操作:

StringStream ss;
ss.write("Hello ").write("world!");

This is a method that most likely modifies a StringStream instance, and returns a reference to a StringStream . 此方法最有可能修改StringStream实例,并返回对StringStream的引用。 So you should return a reference to the instance itself 因此,您应该返回对实例本身的引用

StringStream& StringStream::write(char* text)
{
  // do stuff
  return *this;
}

This allows you to perform chaining: 这使您可以执行链接:

StringStream s;
s.write("foo").write("bar");

That said, I would have expected the write method to take a const char* : 就是说,我本来希望write方法采用const char*

StringStream& write(const char* text);

since the method will presumably not modify the data passed to it, and is required in order to be able to correctly pass string literals such as the "foo" and "bar" in the example. 因为该方法可能不会修改传递给它的数据,所以该方法是必需的,以便能够正确传递示例中的字符串文字,例如"foo""bar"

you can simply return a reference to stringStream class. 您可以简单地返回对stringStream类的引用。 As you are writing a member function of the same class you can simply return pointer to this. 在编写同一类的成员函数时,您只需返回指向该类的指针即可。 For more info about the StringStream class : click here 有关StringStream类的更多信息: 单击此处

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM