复制构造函数 C++ 在析构函数上返回奇怪的字母

copy constructor c++ returns strange letter on destructor

本文关键字:返回 构造函数 C++ 析构函数 复制      更新时间:2023-10-16

>我有这个:

//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是什么?我已经在其他程序上制作了很多次相同的代码,但现在我不明白那是什么?有什么建议吗?

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