use*_*632 1 c++ constructor destructor
我尝试了以下代码(从learncpp.com修改)
#include <iostream>
#include <string>
using namespace std;
class Point2D
{
private:
int m_nX;
int m_nY;
public:
// A default constructor
Point2D()
: m_nX(0), m_nY(0)
{
}
// A specific constructor
Point2D(int nX, int nY)
: m_nX(nX), m_nY(nY)
{
cout<<"Point is created"<<endl;
}
~Point2D(){cout<<"Point is destroyed"<<endl;}
// An overloaded output operator
friend std::ostream& operator<<(std::ostream& out, const Point2D &cPoint)
{
out << "(" << cPoint.GetX() << ", " << cPoint.GetY() << ")";
return out;
}
// Access functions
void SetPoint(int nX, int nY)
{
m_nX = nX;
m_nY = nY;
}
int GetX() const { return m_nX; }
int GetY() const { return m_nY; }
};
class Creature
{
private:
std::string m_strName;
Point2D m_cLocation;
// We don't want people to create Creatures with no name or location
// so our default constructor is private
Creature() { }
public:
Creature(std::string strName, const Point2D &cLocation)
: m_strName(strName), m_cLocation(cLocation)
{
cout<<"Creature is created"<<endl;
}
~Creature(){cout<<"Creature is destroyed"<<endl;}
friend std::ostream& operator<<(std::ostream& out, const Creature &cCreature)
{
out << cCreature.m_strName.c_str() << " is at " << cCreature.m_cLocation;
return out;
}
void MoveTo(int nX, int nY)
{
m_cLocation.SetPoint(nX, nY);
}
};
int main()
{
using namespace std;
cout << "Enter a name for your creature: ";
std::string cName;
cin >> cName;
Creature cCreature(cName, Point2D(4, 7));
while (1)
{
cout << cCreature << endl;
cout << "Enter new X location for creature (-1 to quit): ";
int nX=0;
cin >> nX;
if (nX == -1)
break;
cout << "Enter new Y location for creature (-1 to quit): ";
int nY=0;
cin >> nY;
if (nY == -1)
break;
cCreature.MoveTo(nX, nY);
}
return 0;
}
Run Code Online (Sandbox Code Playgroud)
当我运行程序时,我得到以下内容:
Enter a name for your creature: gabar
Point is created
Creature is created
Point is destroyed
gabar is at: (4,7)
Enter new X location for creature (-1 to quit): 2
Enter new Y location for creature (-1 to quit): 3
gabar is at: (2,3)
Enter new X location for creature (-1 to quit): -1
Creature is destroyed
Point is destroyed
Run Code Online (Sandbox Code Playgroud)
我有两个问题:
为什么称第一个"点被摧毁"?当只有一个"创建点"提示时,为什么有两个提示"点被销毁".
谢谢
我不知道你用什么来跟踪构造函数和析构函数,但我怀疑它没有检测到复制构造函数.
这一行创建了第一个Point2D:
Creature cCreature(cName, Point2D(4, 7));
Run Code Online (Sandbox Code Playgroud)
构造函数Creature通过引用获取它,然后将其分配给它m_cLocation,复制它(调用Point2D我怀疑没有被跟踪的复制构造函数).
第一个Point2D是瞬态的,从未存储过,然后被破坏.m_cLocation在最后被摧毁.
| 归档时间: |
|
| 查看次数: |
111 次 |
| 最近记录: |