【发布时间】:2020-06-27 20:41:00
【问题描述】:
#include<iostream>
#include<cstring>
using namespace std;
class Employee
{
private:
char *firstName;
char *lastName;
static int count;
public:
Employee( const char * const first, const char * const last){
firstName = new char[ strlen( first ) + 1 ];
strcpy( firstName, first );
lastName = new char[ strlen( last ) + 1 ];
strcpy( lastName, last );
count++;
cout << "Employee constructor for " << firstName
<< ' ' << lastName << " called." << endl;
}
~Employee(){
cout << "~Employee() called for " << firstName
<< ' ' << lastName << endl;
delete [] firstName; // release memory
delete [] lastName; // release memory
count--;
}
const char *getFirstName() const{
return firstName;
}
const char *getLastName() const{
return lastName;
}
static int getCount(){
return count;
}
}; // end class Employee
int Employee::count = 0;
main(){
cout<<"Count = "<<Employee::getCount()<<endl;
Employee *e1Ptr = new Employee( "Ahmad", "Ali" );
Employee *e2Ptr = new Employee( "Saeed", "Khalid" );
cout<<"Count = "<<e1Ptr->getCount()<<endl;
cout << "\n\nEmployee 1: "
<< e1Ptr->getFirstName()<<" "<<e1Ptr->getLastName()
<< "\nEmployee 2: "
<< e2Ptr->getFirstName()<<" "<<e2Ptr->getLastName()<<"\n";
delete e1Ptr;
e1Ptr = 0;
delete e2Ptr;
e2Ptr = 0;
cout<<"Count = "<<Employee::getCount()<<endl;
system("pause");
}
Q- 为什么我们需要在 main() 和 class 中进行动态内存分配?在类定义或 main() 函数中分配动态内存是否不够?
Q- 为什么 e1Ptr = 0;而 e2Ptr = 0;正在使用中。
我是新手。所以,请详细说明一下。谢谢
【问题讨论】:
-
忘记 C。C++ 是一种完全不同的语言。
-
没有任何需要......这只是糟糕的编程。 …… PS:
main在 C++ 中需要int的返回类型 -
在 C++ 中,您应该始终使用智能指针(例如 std::unique_ptr、std::shared_ptr、...),而不是手动分配内存。阅读:en.cppreference.com/book/intro/smart_pointers
-
阅读 good C++ programming book,然后是 C++11 标准 n3337,然后是 C++ 编译器(例如 GCC...)和调试器(例如 GDB)的文档。 ..)
-
@LHLaurini。我绝对同意。但也需要大量的练习。见norvig.com/21-days.html
标签: c++ memory dynamic allocation