c为C ++盐我有一个关于初始化和修改类的成员变量的问题 [英] <C++> I have a question about initializing and modifying the member variables of a class

查看:110
本文介绍了c为C ++盐我有一个关于初始化和修改类的成员变量的问题的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这段代码是我正在学习的书的例子。我想知道为什么作者通过应对通过动态分配传递的参数来定义构造函数,留下了SetPersonInfo函数的便利性?



我有什么试过:



This code is the example for the book I'm studying. I'm wondering why the authors defined the constructor by coping the arguments passed in via dynamic allocation, leaving the convenience of the SetPersonInfo function?

What I have tried:

class Person
{
	char * name;
	int age;
public:
	Person(const char * myname, int myage)
	{
		int len = strlen(myname) + 1;
		name = new char[len];
		strcpy(name, myname);
		age = myage;
	}
	Person()
	{
		name = NULL:
		age = 0;
	}
	void SetPersonInfo(const char * myname, int myage)
	{
		name = myname;
		age = myage;
	}
	void ShowPersonInfo() const
	{
		cout << name << ' ' << age << endl;
	}
	~Person()
	{
		delete[]name;
	}
};

推荐答案

这对我来说看起来很糟糕。 SetPersonInfo方法只分配变量即可。问题是析构函数总是删除一个数组。如果名称是文字字符串或其他未分配的数据,那么这将导致异常。显然,这假设传递的名称也已分配。我认为带参数的构造函数应该实现为SetPersonInfo方法,因此它总是复制,这意味着析构函数总是安全的。以下是我认为更好的实现。
This looks like a poor design to me. The SetPersonInfo method just assigns the variables which is OK. The problem is the destructor always deletes an array. If the name was a literal string or other non-allocated data then that would cause an exception. Apparently this assumes the name passed was also allocated. I think the constructor that takes arguments should be implemented as the SetPersonInfo method so it always makes a copy and that would mean the destructor is always safe. Here is what I think is a better implementation.
class Person
{
	char * name;
	int age;
public:
	Person()
	{
		name = NULL:
		age = 0;
	}
	Person(const char * myname, int myage)
	{
		SetInfo( myname, myage );
	}
	void SetInfo(const char * myname, int myage)
	{
		name = strdup( myname );
		age = myage;
	}
	void ShowInfo() const
	{
		cout << name << ' ' << age << endl;
	}
	~Person()
	{
		free( name );
	}
};

是的,我知道它使用的是C风格的文本字符串,但原始文件字符串的strcpy调用也是如此。更好的方法是使用std :: string,然后不需要分配或free。 std :: string类自己管理所有这些。以下是该实现:

Yes, I know it uses C-style text strings but the original did too with its strcpy call. A better way would be to use a std::string and then no allocation or free would be necessary. The std::string class manages all of that itself. Here is that implementation :

class Person
{
	std::string name;
	int age;
public:
	Person()
	{
		age = 0;
	}
	Person(const char * myname, int myage)
	{
		SetInfo( myname, myage );
	}
	void SetInfo(const char * myname, int myage)
	{
		name = myname;
		age = myage;
	}
	void ShowInfo() const
	{
		cout << name << ' ' << age << endl;
	}
	~Person()
	{
	}
};

如你所见,它有点简单。

As you can see, it's a bit simpler.


这篇关于c为C ++盐我有一个关于初始化和修改类的成员变量的问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆