C++ 在C++; 请考虑下面的代码。 #include<iostream> using namespace std; class A { private: int *x; public: A(int a) { cout<<"creating "<<a<<" "<<this<<endl; x = new int; *x = a; } A(A *a) { this->x = a->x; } ~A() { cout<<"destroying "<<x<<endl; delete x; } A *operator+(A a) { return new A(*x + *(a.x)); } void display() { cout<<*x<<endl; } }; int main() { A a(5); A b(10); A c = a + b; cout<<"control returns to main"<<endl; a.display(); b.display(); c.display(); return 0; }
我不明白为什么在控件返回到主函数之前调用析构函数。更重要的是,为什么在C++ 在C++; 请考虑下面的代码。 #include<iostream> using namespace std; class A { private: int *x; public: A(int a) { cout<<"creating "<<a<<" "<<this<<endl; x = new int; *x = a; } A(A *a) { this->x = a->x; } ~A() { cout<<"destroying "<<x<<endl; delete x; } A *operator+(A a) { return new A(*x + *(a.x)); } void display() { cout<<*x<<endl; } }; int main() { A a(5); A b(10); A c = a + b; cout<<"control returns to main"<<endl; a.display(); b.display(); c.display(); return 0; },c++,oop,destructor,C++,Oop,Destructor,我不明白为什么在控件返回到主函数之前调用析构函数。更重要的是,为什么在b上调用它?如果对operator+返回的新对象调用它,这是可以理解的,因为当控件超出对象范围时会调用析构函数 A *operator+(A a) { 按价值接受。也就是说什么时候 a + b; 遇到一个新的b副本,并将其传递给operator+(a) 你看不到一个新的构造,因为你没有一个副本构造函数实现,编译器为你创建了它。否则,您将看到另一个A正在创建 如果你让你的操作符*做这样的参考 A *operator+
b
上调用它?如果对operator+
返回的新对象调用它,这是可以理解的,因为当控件超出对象范围时会调用析构函数
A *operator+(A a)
{
按价值接受。也就是说什么时候
a + b;
遇到一个新的b
副本,并将其传递给operator+(a)
你看不到一个新的构造,因为你没有一个副本构造函数实现,编译器为你创建了它。否则,您将看到另一个A正在创建
如果你让你的操作符*
做这样的参考
A *operator+(A& a)
{
return new A(*x + *(a.x));
}
您将不再看到销毁,因为没有创建副本。您:
- 不要为复制构造函数(此时是编译器生成的)输出“creating”(或者正确地处理您的资源)
- 正在看到临时
被销毁a+b
+
运算符的实现是错误的。请尝试以下方法:
class A
{
private:
int *x;
public:
A(int a)
{
cout << "creating " << a << " " << this << endl;
x = new int;
*x = a;
}
A(const A &a)
{
cout << "copying " << *(a.x) << " " << this << endl;
x = new int;
*x = *(a.x);
}
~A()
{
cout << "destroying " << *x << " " << this << endl;
delete x;
}
A operator+(const A &a)
{
return A(*x + *(a.x));
}
void display()
{
cout << *x << endl;
}
};
A类
{
私人:
int*x;
公众:
A(INTA)
{
cout copies copies在~A
中输出此
(代替或附加x
)。此外,您不应该从操作符+
返回指针。现在这是泄漏。您不需要为此使用指针。
class A
{
private:
int *x;
public:
A(int a)
{
cout << "creating " << a << " " << this << endl;
x = new int;
*x = a;
}
A(const A &a)
{
cout << "copying " << *(a.x) << " " << this << endl;
x = new int;
*x = *(a.x);
}
~A()
{
cout << "destroying " << *x << " " << this << endl;
delete x;
}
A operator+(const A &a)
{
return A(*x + *(a.x));
}
void display()
{
cout << *x << endl;
}
};