提问人:Konstantinos 提问时间:5/22/2020 最后编辑:Konstantinos 更新时间:5/22/2020 访问量:28
复制构造函数 C++ 在析构函数 [duplicate] 上返回奇怪的字母
copy constructor c++ returns strange letter on destructor [duplicate]
问:
我有这个:
//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", "[email protected]");
ApplicationConstructor appConstructor2("3332",(char *)"Maria Paulou", "[email protected]");
appConstructor2 = appConstructor1;
appConstructor2.showData();
}
当我运行它时,我得到了这个:
Code: 3324 Name: Konstantinos Dimos Email: [email protected]
Destruct the object ApplicationConstructor: Konstantinos Dimos
Destruct the object ApplicationConstructor: h�
这些字母 h 是什么?我已经在其他程序上制作了很多次相同的代码,但现在我不明白那是什么?有什么建议吗?
答:
0赞
lostbard
5/22/2020
#1
appConstructor2 = appConstructor1;没有调用复制构造函数,你最终会得到 2 个对象指向同一个分配的字符串,我假设你然后在解构函数中释放它们。
ApplicationConstructor appConstructor1("3332",(char *)"Maria Paulou", "[email protected]"); // calls constructor
ApplicationConstructor appConstructor3 = appConstructor1; // calls the copy
appConstructor3 = appConstructor1; // calls assignment constructor
评论
0赞
Konstantinos
5/22/2020
是的,对不起,你是对的,我是 c++ 的新手,我必须消化这些条款......多谢!!!
评论
std::string
constructorCode
constructorEmail
constructorName
appConstructor2 = appConstructor1;
std::string