复制构造函数 C++ 在析构函数上返回奇怪的字母
copy constructor c++ returns strange letter on destructor
>我有这个:
//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
相关文章:
- 获取从C++中同一类中的构造函数调用的方法返回的值
- C++方法是否可以根据传递给构造函数的参数具有不同的返回类型?
- 类和构造函数中的函数根本不起作用,并且不返回任何错误
- 为什么使用 std::istream_iterator 构造函数返回指针
- 函数返回时,带指针的复制构造函数失败
- 复制构造函数 C++ 在析构函数上返回奇怪的字母
- 在 C++ 中返回新的构造函数(*this)工厂
- 为什么原始卷曲构造函数 {} 不返回右值?
- 为什么我的类工作正常,即使在返回垃圾值作为赋值运算符和空复制构造函数的返回之后
- 删除了所有自动生成的构造函数/运算符的类仍然可以从函数返回吗
- 复制构造函数、按值传递和按值返回、链式操作、编译器
- 使用构造函数从函数返回对象
- 从类似构造函数的调用返回模板化智能指针
- 如何从构造函数返回错误代码?
- 在构造函数处将类对象强制转换为接口始终返回 NULL
- 返回带有另一个类的数据成员的构造函数?遇到转换错误?
- 如果函数按值传递并按值返回,将调用复制构造函数多少次
- 在函数中返回构造函数参数,在返回时调用构造函数
- 返回构造函数的类型定义-如何修复此标头
- 我可以通过返回构造函数直接返回对象吗?