C++ 我是否正确构建了这些引用和指针函数?如果是这样,我如何显式调用析构函数?
参考功能:C++ 我是否正确构建了这些引用和指针函数?如果是这样,我如何显式调用析构函数?,c++,C++,参考功能: // the getDept() function shall be defined as a reference function. That is, a call to this function will copy the // member variable m_iDeptID into the int variable referenced by the function argument void EmployeeRecord::getDept(int& d) {
// the getDept() function shall be defined as a reference function. That is, a call to this function will copy the
// member variable m_iDeptID into the int variable referenced by the function argument
void EmployeeRecord::getDept(int& d)
{
d = m_iDeptID;
}
// the getSalary() function shall be defined as a pointer function. That is, a call to this function will copy the
// member variable m_dSalary into the int variable pointed to by the function argument
void EmployeeRecord::getSalary(double *sal)
{
*sal = m_dSalary;
}
// destructor - cleans up and deallocates any memory that pointers within this class may have referenced to
EmployeeRecord::~EmployeeRecord(){}
指针函数:
// the getDept() function shall be defined as a reference function. That is, a call to this function will copy the
// member variable m_iDeptID into the int variable referenced by the function argument
void EmployeeRecord::getDept(int& d)
{
d = m_iDeptID;
}
// the getSalary() function shall be defined as a pointer function. That is, a call to this function will copy the
// member variable m_dSalary into the int variable pointed to by the function argument
void EmployeeRecord::getSalary(double *sal)
{
*sal = m_dSalary;
}
// destructor - cleans up and deallocates any memory that pointers within this class may have referenced to
EmployeeRecord::~EmployeeRecord(){}
析构函数(我在函数中没有任何delete语句或任何内容):
我尝试显式调用析构函数:
EmployeeRecord Employee1;
Employee1.~EmployeeRecord();
因此,我的问题是:
(1) 我的引用函数和指针函数是否与其描述一致?
(2) 如果是,我应该在析构函数的块中放入什么代码,以便显式调用析构函数,并且它成功地“清理并释放此类中指针可能引用的任何内存”(如果事实上,析构函数体中有任何我需要放入的内容) 依次:
getDept(int&d)
与它的描述一致,但是getSalary(double*d)
不完全一致:描述说它应该将值复制到函数参数指向的int变量中
getSalary
则应采用int*
参数,而不是double*
参数,并且该方法应执行适当的强制转换。(不过,这看起来确实有点奇怪——肯定不是说double而不是int?)int
s和double
s等等。是否有任何成员是指针我认为这个
*sal=m_dSalary代码>应该是*sal=*m_dSalary代码>此代码毫无意义。如果您以正常方式创建对象,那么为什么要显式调用析构函数?(这样做只会导致不好的结果。)这与您的成员函数有什么关系?为什么要调用析构函数?您的对象是本地的(在堆栈上)->析构函数将被调用您的函数返回的析构函数:您可能希望在尝试写入任何内容之前检查sal==nullptr
。@Marcin m_dSalary不是指针成员变量不是指针。有两个字符数组,但我不认为我必须删除它们(当我尝试时,我得到了一个破例)。而且我认为描述应该是双重的。。。如果它是int类型,那就很奇怪了。析构函数应该释放对象实例所声明的任何资源;因此,如果这些字符数组是用new[]
在堆上分配的,那么它们应该被delete[]
处理;如果分配给他们的是malloc
,他们应该被分配给free
;等等。如果它们只是数组成员变量,那么就没什么可做的了:)太棒了!那么我所有的函数都是根据注释掉的规范正确构建的?我不需要显式调用析构函数?这是一种非常罕见的情况,需要显式调用析构函数。当对象超出范围或被显式删除时,会自动调用它们。鉴于问题中可见的信息,看起来你很好!谢谢,你帮了我大忙。