warning C4355: “this”: 用于基成员初始值设定项列表

春天到了冬天还远吗 2011-07-27 10:18:22

我在想,为什么会出现这个警告,各位达人指点一下

class B;
class A
{
B* m_pB;
public:
A(B* pB)
{
m_pB = pB;
}
};
class B
{
A a;
public:
B() : a(this)
{

}
};


int _tmain(int argc, _TCHAR* argv[])
{
B a;
return 0;
}

...全文
726 7 打赏 收藏 转发到动态 举报
写回复
用AI写文章
7 条回复
切换为时间正序
请发表友善的回复…
发表回复
AI1982 2014-02-09
  • 打赏
  • 举报
回复
构造a时b还没有构造完毕,编译器不能探测a构造的实现细节,所以给出的只是警告。要想消除警告,就得把a放在花括号里构造。
luciferisnotsatan 2011-07-27
  • 打赏
  • 举报
回复
Error Message
'this' : used in base member initializer list


The this pointer is valid only within nonstatic member functions. It cannot be used in the initializer list for a base class.

The base-class constructors and class member constructors are called before this constructor. In effect, you've passed a pointer to an unconstructed object to another constructor. If those other constructors access any members or call member functions on this, the result will be undefined. You should not use the this pointer until all construction has completed.

This is a level-1 warning under Microsoft extensions (/Ze) and a level-4 warning otherwise.

The following sample generates C4355:

Copy Code
// C4355.cpp
// compile with: /W1 /c
#include <tchar.h>

class CDerived;
class CBase {
public:
CBase(CDerived *derived): m_pDerived(derived) {};
~CBase();
virtual void function() = 0;

CDerived * m_pDerived;
};

class CDerived : public CBase {
public:
CDerived() : CBase(this) {}; // C4355 "this" used in derived c'tor
virtual void function() {};
};

CBase::~CBase() {
m_pDerived -> function();
}

int main() {
CDerived myDerived;
}

ouyh12345 2011-07-27
  • 打赏
  • 举报
回复
参数应该是某个类型吧
ryfdizuo 2011-07-27
  • 打赏
  • 举报
回复
错误提示已经很明显了么。B的构造函数中使用this指针。
http://cboard.cprogramming.com/cplusplus-programming/99530-warning-c4355-used-base-member-initializer-list.html
  • 打赏
  • 举报
回复
用 dev cpp试了下,没这个警告
  • 打赏
  • 举报
回复
[Quote=引用 3 楼 dizuo 的回复:]
错误提示已经很明显了么。B的构造函数中使用this指针。
http://cboard.cprogramming.com/cplusplus-programming/99530-warning-c4355-used-base-member-initializer-list.html
[/Quote]
看到了呀,我想问,构造函数中为什么不能用this指针,不过你给的地址可能有说明,我去研究研究

64,637

社区成员

发帖
与我相关
我的任务
社区描述
C++ 语言相关问题讨论,技术干货分享,前沿动态等
c++ 技术论坛(原bbs)
社区管理员
  • C++ 语言社区
  • encoderlee
  • paschen
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
  1. 请不要发布与C++技术无关的贴子
  2. 请不要发布与技术无关的招聘、广告的帖子
  3. 请尽可能的描述清楚你的问题,如果涉及到代码请尽可能的格式化一下

试试用AI创作助手写篇文章吧