c ++这个指针问题

Yos*_*oss 2 c++ object-construction this-pointer

这是我想做的事情(可能不是最好的事情)能够调用一些类构造函数,它接收一个指向正在调用的类的指针(ufff !!!).代码看起来更好,就像我在C#中所做的那样.

public class SomeClass
{
   SomeOtherClass someOtherClass;

   //Constructor
   public SomeClass(SomeOtherClass someOtherClass)
   {
      this->someOtherClass = someOtherClass;
   }
}

public class SomeOtherClass
{

   public SomeOtherMethod()
   {
      SomeClass c = new SomeClass(this);
   }
}
Run Code Online (Sandbox Code Playgroud)

那么,如何在c ++中实现相同的结果呢?Thanx提前.

iam*_*ind 5

class SomeOtherClass;  // forward declaration (needed when used class is not visible)
class SomeClass
{
   SomeOtherClass *someOtherClass;
public:
   SomeClass(SomeOtherClass *some) : someOtherClass(some)
   {}  // this is called initialization at constructor (not assignment)
}

class SomeOtherClass
{
public:
   SomeOtherMethod()
   {
      SomeClass *c = new SomeClass(this);
   }
}
Run Code Online (Sandbox Code Playgroud)

在回答了上述要求之后,还要注意在C++中,您实际上不需要始终声明对象new.如果你宣布,

SomeOtherClass someOtherClass;
Run Code Online (Sandbox Code Playgroud)

那意味着你有一个SomeOtherClass名为的对象someOtherClass.