#include<iostream>
using namespace std;
class Integer
{
public:
int integer;
Integer()
{
integer = 0;
cout << "Default constructor called with this pointer "
<< static_cast<void*>(this) << std::endl;
}
Integer(int i) : integer(i)
{
cout << "Constructor called with this pointer "
<< static_cast<void*>(this) << std::endl;
}
Integer(const Integer& Int)
{
cout << "Copy constructor with this pointer "
<< static_cast<void*>(this) << std::endl;
this->integer = Int.integer;
}
const Integer operator=(const Integer& rhs)
{
if (this == &rhs)
return *this;
this->integer = rhs.integer;
cout << "Assignment operator with this pointer "
<< static_cast<void*>(this) << std::endl;
return *this;
}
};
int main()
{
Integer i1;
Integer i2(6);
Integer i3 = i2; // equal to i3(i2), call i3's copy construstor but not the assignment operator
i1 = i2; // call i1's assignment operator, and the temporary object's copy constructor for return.
cout << "i1: " << static_cast<void*>(&i1) << endl;
cout << "i2: " << static_cast<void*>(&i2) << endl;
cout << "i3: " << static_cast<void*>(&i3) << endl;
return 0;
}
输出:
Default constructor called with this pointer 00AAFCBC
Constructor called with this pointer 00AAFCB0
Copy constructor with this pointer 00AAFCA4
Assignment operator with this pointer 00AAFCBC
Copy constructor with this pointer 00AAFBD8
i1: 00AAFCBC
i2: 00AAFCB0
i3: 00AAFCA4
本文深入探讨了C++中类成员的默认构造函数、带参构造函数、拷贝构造函数以及赋值运算符的实现与使用,通过实例代码展示了这些关键概念的应用。
524

被折叠的 条评论
为什么被折叠?



