C++复制构造函数和析构函数 我正在学习C++中的构造函数和析构函数;帮助我抓住我的错误,即使它们是愚蠢的 这是我编写的一个代码,用C++中的类进行加法运算;这将创建两个数据类型num的summand,并使用构造函数sum来执行两个数字的求和;然而,当一切顺利时,我偶然发现为num创建了一个副本构造函数,虽然不是必需的,但仍然是为了练习。。。如果没有类sum的动态对象,那么在不删除复制构造函数的情况下,无论如何都不可能运行代码。。。帮助我改进我的代码和下面代码中的错误;我还想知道如何在这个程序中使用复制构造函数;问题是在析构函数中,删除操作在同一块内存上执行了多次
这是我的密码C++复制构造函数和析构函数 我正在学习C++中的构造函数和析构函数;帮助我抓住我的错误,即使它们是愚蠢的 这是我编写的一个代码,用C++中的类进行加法运算;这将创建两个数据类型num的summand,并使用构造函数sum来执行两个数字的求和;然而,当一切顺利时,我偶然发现为num创建了一个副本构造函数,虽然不是必需的,但仍然是为了练习。。。如果没有类sum的动态对象,那么在不删除复制构造函数的情况下,无论如何都不可能运行代码。。。帮助我改进我的代码和下面代码中的错误;我还想知道如何在这个程序中使用复制构造函数;问题是在析构函数中,删除操作在同一块内存上执行了多次,c++,class,constructor,destructor,custom-data-type,C++,Class,Constructor,Destructor,Custom Data Type,这是我的密码 #include<iostream> #include<new> using namespace std; class num { public: int *a; num(int x) { try { a=new int; } catch(bad_alloc xa) { cout<<"1";
#include<iostream>
#include<new>
using namespace std;
class num
{
public:
int *a;
num(int x)
{
try
{
a=new int;
}
catch(bad_alloc xa)
{
cout<<"1";
exit(1);
}
*a=x;
}
num(){ }
num(const num &ob)
{
try
{
a=new int;
}
catch(bad_alloc xa)
{
cout<<"1''";
exit(2);
}
*a=*(ob.a);
}
~num()
{
cout<<"Destruct!!!";
delete a;
}
};
class sum:public num
{
public:
int add;
sum(num n1,num n2)
{
add=*(n1.a)+*(n2.a);
}
int getsum()
{
return add;
}
};
int main()
{
num x=58;
num y=82;
sum *s=new sum(x,y);
cout<<s->getsum();
delete s;
return 0;
}
我可能会错过一些东西-没有使用new/delete太长时间,但尝试更正我注意到的所有内容 注意,始终使用智能指针
#include <iostream>
#include <exception>
#include <new>
using namespace std;
int* allocate(const char* err_msg, int exit_code)
{
int* a = nullptr;
try
{
a = new int;
}
catch (bad_alloc&)
{
cout << err_msg << endl;
exit(exit_code);
}
return a;
}
class num
{
int* a = nullptr; // always should be initialized here
public:
num() noexcept : a(nullptr) // or here
{}
/*explicit*/ num(int x) : a(allocate("1", 1))
{
*a = x;
}
num(const num& ob) : a(allocate("1''", 2))
{
*a = *(ob.a);
}
// rule of zero/three/five
// default copy assignment will copy pointer and one int will be leaked and one will be deleted twice
num& operator =(const num& ob)
{
if (&ob == this)
{
return *this;
}
*a = *(ob.a);
return *this;
}
~num()
{
cout << "Destruct!!!";
delete a;
a = nullptr; // usefull for debug
}
int value() const
{
if (a == nullptr)
{
throw runtime_error("a == nullptr");
}
return *a;
}
};
class sum
{
int add = 0;
public:
sum(const num& n1, const num& n2)
{
add = n1.value() + n2.value();
}
int getsum() const
{
return add;
}
};
int main()
{
const num x = 58;
const num y = 82;
const sum* s = new sum(x, y);
cout << s->getsum() << endl;
delete s;
return 0;
}
对于代码审查,您可能会考虑到Num {}这是非常错误的。不能让指针数据成员处于未初始化状态。为什么sum需要从num继承?sumnum n1、num n2更喜欢按const num&取而代之。sumcontnum&n1、constnum&n2我认为num不需要保存int*,而不仅仅是一个int,或者它根本不存在。只需操作intsThanks,感谢您的帮助;再一个;由于我不熟悉构造函数和异常,所以请您解释num noexcept:anullptr行以及0 3和5的规则好吗?编译过程中会出现几十个错误;我无法调试这些errors@ArijitDey你用哪种编译器?下面是对0/3/5规则的解释:@ArijitDey num noexcept:anullptr是一个默认构造函数,用0初始化一个。