为什么有两个额外的析构函数调用,因为我只创建了两个对象并使用重载赋值运算符和增量运算符
Why are there two extra calls to destructor as I have created only two objects and using overloaded assignment operator and increment operator
#include <iostream>
using namespace std;
class loc{
int iVAL;
public:
loc(int i){
cout<<"inside parameter constructor"<<endl;
iVAL = i;
}
loc(){
iVAL = 0;
cout<<"inside default constructor"<<endl;
}
loc operator+(loc ob1){
loc temp;
temp.iVAL = iVAL + ob1.iVAL;
return temp;
}
void show(){
cout<<iVAL;
}
loc operator++(){
cout<<"inside pre increment"<<endl;
++iVAL;
return *this;
}
loc operator++(int x){
cout<<"inside post increment"<<endl;
iVAL++;
return *this;
}
loc operator=(loc &ob){
cout<<"inside assignment"<<endl;
iVAL = ob.iVAL;
return *this;
}
~loc(){
cout<<this->iVAL<<endl;
cout<<"inside loc destructor"<<endl;
}
};
int main(int argc, char* argv[]){
loc ob1(10),ob3;
ob3 = ++ob1;
return 0;
}
输出:
内部参数构造函数
默认构造函数
内部 内部预增量
内部分配
11
LOC 析构函数内部//对析构函数
的额外调用 11
LOC 析构函数内部//对析构函数
的额外调用 11
LOC 析构函数
内部 11
LOC 析构函数
内部
这是因为
ob3 = ++ob1;
更仔细地查看此代码
loc operator++(({ cout<<"内部预指控"<<p>那么,您可以做些什么来避免此额外副本。您可以通过引用返回
const loc& operator++(){
cout<<"inside pre incriment"<<endl;
++iVAL;
return *this; <--- you create a new copy and send it back
}
上面的代码通过引用返回,const 指针是防止其他人修改您的值。
但是,您为预增量编写的代码是错误的它应该在递增之前重新调整值。
所以代码应该是这样的
loc operator++(){
cout<<"inside pre incriment"<<endl;
int temp = iVAL;
++iVAL;
return temp; <--- you create a new copy and send it back
}
在这种情况下,您不能通过引用返回临时变量之间的 temp。
相关文章:
- 如何返回一个类的两个对象相加的结果
- 为什么Mat类的两个对象可以在不重载运算符+的情况下添加
- 停止cmake target_link_libraries将插件中静态库的两个对象文件链接到静态库本身
- 为什么C++在将一个对象复制到另一个对象时需要对这两个对象进行低级常量限定
- int数据类型的指针指向的是什么,如果是一个类的私有数据成员,我们创建了该类的两个对象?
- 具有相同特征的两个对象是否只在内存中存储一次?无论定义它们的函数是什么,都是不同的
- 如何在Qt中连接来自不同窗口的两个对象?
- C++两个对象,其中包含指向同一数组不同部分的指针
- 为什么将两个对象分配给另一个对象后,两个对象不一样?
- C++:在另外两个对象之间共享一个对象
- 在单元测试中,如何在不使用 operator== 的情况下比较两个对象,这可能会错过新成员?
- 同一类的两个对象相互引用
- 将类对象传递给两个对象
- 如何调用运算符函数添加两个对象?
- 让一个名为A的类.传递以下两个对象有什么区别:(a)obj1和(b)obj1()
- 比较矢量迭代中的两个对象C
- 当我有两个对象时<<如何重载运算符?(有关系)
- 声明一个模板函数,将模板类友元的两个对象(仅)带到这两个专用化
- 使用指针将两个对象(每个都与一个类)相关联
- 比较类的两个对象之间的数据