对"this"指针的操作是否会调用构造函数?
我有一个构造函数定义如下
Cents(int cents)
{
cout<<"in cents constructor\n";
m_cents = cents;
}
friend Cents operator + (const Cents &c1, const Cents &c2)
{
return Cents(c1.m_cents + c2.m_cents);
}
Cents operator ++ (int)
{
cout<<"In c++ function\n";
Cents c(m_cents);
*this = *this + 1 ;
return c;
}
Run Code Online (Sandbox Code Playgroud)
在主要功能我... ...
Cents c;
cout<<"Before post incrementing\n";
c++; //This part is calling the constructor thrice
Run Code Online (Sandbox Code Playgroud)
现在,如果我正在做一些像*this = *this + 1
.它调用此构造函数两次.
究竟是怎么回事.是否*this
创建临时对象并将值分配给原始对象?
Raf*_*cki 11
不,取消引用指针不会创建任何新对象.
Hovever,如果你operator+
只为你的类的实例定义,将会有一个新的实例构造 1
,因为构造函数Cents(int cents)
没有标记为显式.
归档时间: |
|
查看次数: |
210 次 |
最近记录: |