我们可以在构造函数中使用“this”指针 [英] Can we use 'this' pointer inside constructor

查看:225
本文介绍了我们可以在构造函数中使用“this”指针的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述


可能重复:

C ++在构造函数中使用此指针


标题,我可以像下面的代码一样做吗?

  class A; 

B类{
public:
B(A * p);
...
};

A类{
B m;
public:
A():m(this){}
〜A(){}
};


解决方案

Possible Duplicate:
C++ using this pointer in constructors

Like the title, may I do something like the following code?

class A;

class B {
public:
    B(A* p);
    ...
};

class A {
    B m;
public:
    A():m(this){}
    ~A(){}
};

解决方案

Yes, you can passed a pointer to an object currently under construction. But you have to keep in mind, that the object isn't constructed completely yet. So basically what B can do in it's c'tor is store the pointer for later use.

An example where this is often used, is a std::stream and a stream buffer.

这篇关于我们可以在构造函数中使用“this”指针的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆