[英]C++ assigning to a object
Why the last variable c do not print anything.为什么最后一个变量 c 不打印任何内容。 I know that is caused by destructors but i can't really find out why.
我知道这是由析构函数引起的,但我真的不知道为什么。 I thought that destructors only works when is called or is the end of function, program.
我认为析构函数仅在被调用或 function 程序结束时才起作用。
.....//
class Int{
private:
int a;
public:
Int(): a{0}{}
Int(int s):a{s}{}
Int(const Int& va) : a{va.a} { }
Int& operator=(const Int& r){ a= r.a; }
~Int(){delete this;}
int get() const{return a;}
};
ostream& operator<<(ostream& os, const Int& obj)
{
os<<obj.get();
return os;
}
istream& operator>>(istream& is, Int& obj)
{
.....//
}
Int operator+(const Int& rhs,const Int& r)
{
return Int(rhs.get()+r.get());
}
Int operator-(const Int& rhs,const Int& r)
{
return Int(rhs.get()-r.get());
}
Int operator*(const Int& rhs,const Int& r)
{
return Int(rhs.get()*r.get());
}
Int operator/(const Int& rhs,const Int& r)
{
return Int(rhs.get()/r.get());
}
int main(){
Int a = 10;
Int b = a;
cout<<b;
Int k = a+b;
Int c= k*b;
cout<<" "<<k<<" "<<c;
c=300;
cout<<" "<<c;
}
In advance thanks for explanation提前感谢您的解释
Your job in the destructor is to clean up any resources you've allocated or inherited ownership of as per the RAII rules of C++ .您在析构函数中的工作是根据 C++ 的 RAII 规则清理您分配或继承所有权的任何资源。 It is not to delete yourself.
不是要删除自己。 That is not your job.
那不是你的工作。
Since you have no allocated resources, your job is pretty simple:由于您没有分配资源,因此您的工作非常简单:
~Int(){}
Nothing to it, literally.从字面上看,没什么。 In fact you can skip having a destructor completely.
事实上,你可以完全跳过析构函数。 These are only necessary if you have:
仅当您有以下情况时才需要这些:
delete
or transfer ownership ofdelete
或转移所有权的指针
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.