C++ classes getting value using pointers and strcpy [closed]

一曲冷凌霜 提交于 2020-01-08 01:25:34

问题


I am trying to understand C++. Can anybody explain what this code does exactly, I understood that it is some type of setter and getter in Java but I am not sure.

Comm::Comm(const char* id)
{
strcpy(this->id, id);
}


char* Comm::getId()
{
   return id;
}

回答1:


What does this code do?

It burns the eyes of children.

The assumption here is that the class Comm has a member variable of type char* or char[N]. There is no "setter" per se, but Comm's constructor attempts to copy its input to that member variable. The getId function is a getter for this member variable.

Depending on the rest of the code, this could be totally flawed due to lack of memory allocation, lack of memory de-allocation, and lack of copy semantics. At best the member is an array and then the lack of range checking in the strcpy call is a serious security risk.

The class would be much better redesigned with the use of std::string.

I would not encourage you to learn from this code snippet.

Instead, learn from a good book.



来源:https://stackoverflow.com/questions/20939163/c-classes-getting-value-using-pointers-and-strcpy

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!