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

copy constructor c++ returns strange letter on destructor [duplicate]

提问人:Konstantinos 提问时间:5/22/2020 最后编辑:Konstantinos 更新时间:5/22/2020 访问量:28

问:

我有这个:

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

C++ 指针复制 构造函数

评论

1赞 Some programmer dude 5/22/2020
你使用(我假设)for 和 ,但不使用 .为什么?如果你这样做了,你就不需要一个显式的复制构造函数或析构函数。std::stringconstructorCodeconstructorEmailconstructorName
0赞 Some programmer dude 5/22/2020
另请注意,这是一项作业,而不是复制结构。appConstructor2 = appConstructor1;
0赞 Zig Razor 5/22/2020
我们需要析构函数的代码和 showData() 函数
0赞 Konstantinos 5/22/2020
我添加了析构函数和 ShowData() 方法。我必须使用 ConstructorName 属性上的指针来制作它
0赞 Peter 5/22/2020
查找“三法则”。如果必须定义复制构造函数、赋值运算符或析构函数之一,则必须定义这三者。您已经显示了复制构造函数的定义,但未显示析构函数的定义(直到您最近一次编辑),也没有显示赋值运算符的定义。弄错了会解释你的症状。或者,更好的是,查找“零规则”,并在此基础上自己使用而不是管理动态分配的内存。std::string

答:

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++ 的新手,我必须消化这些条款......多谢!!!