函数在c ++中返回此指针

Gau*_*mar 5 c++

第一个代码:

#include <iostream>
using namespace std;
class demo
{
  int a;
public:
  demo():a(9){}
  demo& fun()//return type isdemo&
  {
    return *this;
  }
};

int main()
{
  demo obj;
  obj.fun();
  return 0;
}
Run Code Online (Sandbox Code Playgroud)

第二个代码:

#include <iostream>
using namespace std;
class demo
{
  int a;
public:
  demo():a(9){}
  demo fun()//return type is demo
  {
    return *this;
  }
};

int main()
{
  demo obj;
  obj.fun();
  return 0;
}
Run Code Online (Sandbox Code Playgroud)

这两个代码有什么区别,因为两个代码都在gcc中工作?我是新来的,所以请原谅我,如果我的提问方式是错误的.

Eri*_*rik 8

demo & fun()返回对当前对象的引用.demo fun()返回一个对象,通过复制当前对象生成.

  • @gautam:两者都是_valid_,但他们做了不同的事情.它们是否"正确"取决于您希望代码执行的操作.(至于你的问题,不应该是同一个指针.) (2认同)

Xeo*_*Xeo 5

除了@Erik关于返回类型的说法之外,-pointer上的一些小this例子:
以下是等价的:

struct my_struct{
  my_struct* get_this() const { return this; }
};

my_struct obj;
my_struct* obj_this = ob.get_this();

std::cout << std::boolalpha; // to display true/false instead of 1/0
std::cout << "&obj == obj_this = " << &obj == obj_this << "\n";
Run Code Online (Sandbox Code Playgroud)

this指针正好指向该对象,你可以把它作为一个隐藏的参数.在C方式中更容易理解:

typedef struct my_struct{
  int data;
  // little fidgeting to simulate member functions in c
  typedef void (*my_struct_funcptr)(struct my_struct*,int);
  my_struct_funcptr func;
}my_struct;
// C++ does something similar to pass the this-pointer of the object
void my_struct_func(my_struct* this, int n){
  this->data += n;
}

my_struct obj;
obj.data = 55;
// see comment in struct
obj.func = &my_struct_func;
obj.func(&obj, 15);
//       ^^^^ - the compiler automatically does this for you in C++
std::cout << obj.data; // displays 70
Run Code Online (Sandbox Code Playgroud)


Dav*_*eas 5

两者均有效,但有所不同。在第一种情况下demo& fun(),将返回对同一对象的引用,在第二种情况下,将创建一个新对象。两者相同,但语义不同,请运行以下示例:

#include <iostream>
struct test {
  int x;
  test() : x() {}
  test& foo() { return *this; }
  test bar() { return *this; }
  void set( int value ) { x = value; }
};
int main() {
  test t;
  t.foo().set( 10 );             // modifies t
  t.bar().set( 5 );              // modifies a copy of t
  std::cout << t.x << std::endl; // prints 10
}
Run Code Online (Sandbox Code Playgroud)