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