【问题标题】:copy constructor c++ returns strange letter on destructor [duplicate]复制构造函数c ++在析构函数上返回奇怪的字母[重复]
【发布时间】:2020-05-22 10:54:38
【问题描述】:

我有这个:

//Constructor
ApplicationConstructor::ApplicationConstructor(string constructorCode, char *constructorName, string constructorEmail){
int i = strlen(constructorName);
ConstructorName = new char[i+1];
strncpy(ConstructorName, constructorName, (i+1));
ConstructorCode = constructorCode;
ConstructorEmail = constructorEmail;
}

//Copy constructor
ApplicationConstructor::ApplicationConstructor(const ApplicationConstructor &applicationConstructor){
int i = strlen(applicationConstructor.ConstructorName);
ConstructorName = new char[i+1];
strncpy(ConstructorName, applicationConstructor.ConstructorName, (i+1));
ConstructorCode = applicationConstructor.ConstructorCode;
ConstructorEmail = applicationConstructor.ConstructorEmail;   
}

ApplicationConstructor::~ApplicationConstructor(){
   cout << "Destruct the object ApplicationConstructor: " << this- 
   >ConstructorName << endl;
   delete[] this->ConstructorName;
} 

//Show the Application Constructor Data Method
void ApplicationConstructor::showData(){
   cout << " Code: " << this->ConstructorCode         
        << " Name: " << this->ConstructorName
        << " Email: " << this->ConstructorEmail
        << endl;
 } 

还有这个:

int main(int argc, char** argv) {    
ApplicationConstructor appConstructor1("3324",(char *)"Konstantinos Dimos", "konstantinos@uniwa.gr");
ApplicationConstructor appConstructor2("3332",(char *)"Maria Paulou", "nikos@uniwa.gr");

appConstructor2 = appConstructor1;
appConstructor2.showData();
}

当我运行它时我得到了这个:

 Code: 3324 Name: Konstantinos Dimos Email: konstantinos@uniwa.gr
 Destruct the object ApplicationConstructor: Konstantinos Dimos
 Destruct the object ApplicationConstructor: h�

这些字母h是什么?我在其他程序上做了很多次相同的代码,但现在我不明白那是什么?有什么建议吗?

【问题讨论】:

  • 您将std::string(我假设)用于constructorCodeconstructorEmail,但不适用于constructorName。为什么?如果你这样做了,你就不需要显式的复制构造函数或析构函数。
  • 另请注意,appConstructor2 = appConstructor1; 是一个assignment,而不是一个复制构造。
  • 我们需要析构函数和showData()函数的代码
  • 我添加了析构函数和 ShowData() 方法。我必须使用 ConstructorName 属性上的指针来实现
  • 查找“三法则”。如果您必须定义复制构造函数、赋值运算符或析构函数之一,则必须定义所有三个。您已经显示了复制构造函数的定义,但没有显示析构函数的定义(直到您最近的编辑),也没有显示赋值运算符的定义。弄错会解释你的症状。或者,更好的是,查找“零规则”,并在此基础上使用std::string,而不是自己管理动态分配的内存。

标签: c++ pointers copy-constructor


【解决方案1】:

appConstructor2 = appConstructor1;没有调用复制构造函数,你最终会得到 2 个指向同一个分配字符串的对象,我假设你然后在解构函数中释放它。

ApplicationConstructor appConstructor1("3332",(char *)"Maria Paulou", "nikos@uniwa.gr"); // calls constructor

ApplicationConstructor appConstructor3 = appConstructor1; // calls the copy

appConstructor3 = appConstructor1; // calls assignment constructor

【讨论】:

  • 是的,对不起,你是对的,我是 C++ 新手,我必须消化这些术语......非常感谢!!!
猜你喜欢
  • 1970-01-01
  • 2015-07-24
  • 2020-07-02
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-03-23
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多