cpp一些基本问题
我的任务如下: 创建具有 char*name 和 int Age 的 Person 类。使用变量动态分配内存实现构造函数、析构函数、函数 init 和友元函数 show。然后将这个类转化为头文件和cpp文件并在其他程序中实现。好的,这是我的 Person 类:
#include <iostream>
using namespace std;
class Person {
char* name;
int age;
public:
Person(){
int size=0;
cout << "Give length of char*" << endl;
cin >> size;
name = new char[size];
age = 0;
}
Person::~Person(){
cout << "Destroying resources" << endl;
delete [] name;
delete take_age();
}
friend void show(Person &p);
int* take_age(){
return &age;
}
char* take_name(){
return name;
}
void init(char* n, int a) {
name = n;
age = a;
}
};
void show(Person *p){
cout << "Name: " << p->take_name() << "," << "age: " << p->take_age() << endl;
}
int main(void) {
Person *p = new Person;
p->init("Mary", 25);
show(p);
system("PAUSE");
return 0;
}
现在带有标头/实现部分:
- 我需要在头文件/实现文件中引入构造函数吗?如果是 - 怎么办?
- 我的 show() 函数是一个友好的函数。我应该以某种方式考虑它吗?
我已经未能在考试中返回此任务,但我仍然想知道如何实现它。
My task was as follows :
Create class Person with char*name and int age. Implement contructor using dynamic allocation of memory for variables, destructor, function init and friend function show. Then transform this class to header and cpp file and implement in other program. Ok so here's my Person class :
#include <iostream>
using namespace std;
class Person {
char* name;
int age;
public:
Person(){
int size=0;
cout << "Give length of char*" << endl;
cin >> size;
name = new char[size];
age = 0;
}
Person::~Person(){
cout << "Destroying resources" << endl;
delete [] name;
delete take_age();
}
friend void show(Person &p);
int* take_age(){
return &age;
}
char* take_name(){
return name;
}
void init(char* n, int a) {
name = n;
age = a;
}
};
void show(Person *p){
cout << "Name: " << p->take_name() << "," << "age: " << p->take_age() << endl;
}
int main(void) {
Person *p = new Person;
p->init("Mary", 25);
show(p);
system("PAUSE");
return 0;
}
And now with header/implementation part :
- do I need to introduce constructor in header/implementation files ? If yes - how?
- my show() function is a friendly function. Should I take it into account somehow ?
I already failed to return this task on my exam, but still I'd like to know how to implement it.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(8)
通过从
char *
切换到std::string
可以解决您的许多问题。你会很高兴你这么做了。std::string
类负责内存分配、释放以及复制。如果这是家庭作业,请说服您的教授为初学者使用
std::string
并为指针部分保留char *
。还要提醒您的教授,C++ 语言与 C 语言不同。这是这些领域之一。Solve many of your issues, by switching from
char *
tostd::string
. You'll be glad you did.The
std::string
class takes care of memory allocation, and deallocation as well as copying.If this is homework, convince your professor to use
std::string
for beginners and savechar *
for the section on pointers. Also remind your professor that the C++ langauge is different than the C language. This is one of those areas.使用
delete
或delete[]
时不需要*
。只需向其提供一个指针变量即可,例如。此外,您的
take_age
成员声称返回int*
但您实际上返回int
成员本身。如果您想这样做,您需要使用&
获取会员的地址。正如 @Jerry 所评论的,这不是您想要在这里做的事情。You don't need a
*
when usingdelete
ordelete[]
. Just supply a pointer variable to it eg.Also, your
take_age
member claims to return aint*
but you actually return theint
member itself. You need to take the address of the member using&
if you want to do that. As @Jerry has commented this is not what you want to do here.尽管该网站上的一些人显然认为这是完全可以接受的,但很好的做法(请参阅
恕我直言,这就是您应该采取的第一步。
Although some on this site apparently think it is completely acceptable, good practice (see Can a constructor return a NULL value?), you should really refrain from doing things like stream operations within the constructor of your object. Do that stream reading outside and then call the function with the results.
That is, IMHO, the first step you should take.
在典型情况下,管理一个指针和动态分配的内存块(例如本例中的名称)对于一个类来说就足够了。因此,Thomas Matthews 是对的:在这种情况下你真的应该使用字符串。如果您要自己处理它,您仍然应该将该责任拆分到它自己的类中,并将该类的对象嵌入到您的 Person 对象中。如果有的话,std::string 已经尝试做太多事情了;你最好做一些少做的事,而不是多做的事。
您的删除应该与您的分配完全匹配。在这种情况下,唯一的分配是:
所以唯一的删除应该是:
就
friend
函数而言,您通常希望将友元声明放在类定义内,但将函数定义放在类定义之外:还有其他可能性,但这就是总体思路。特别是,朋友从来都不是成员函数。您拥有的是一个名为
show
的(全局)函数的声明和一个完全独立的成员函数的定义——它们碰巧具有相同的名称,但实际上根本不是同一个函数。这表明了另一点:常量正确性。您将参数作为对 Person 的引用传递。除非它要修改 Person 对象(在这种情况下,show() 似乎是一个糟糕的名称选择),否则它可能应该引用 const 对象。同样的一般思想也适用于
take_age()
——因为它只检索一个值,所以它应该是一个const
函数:我可能已经尝试涵盖太多了,所以我暂时闭嘴...
In a typical case, managing a pointer and block of dynamically allocated memory (such as the name in this case) is enough responsibility for one class. As such, Thomas Matthews is right: you should really use string in this case. If you're going to handle it yourself, you should still split that responsibility off into a class of its own, and embed an object of that class into your Person object. If anything,
std::string
already tries to do too much; you'd be better off with something that does less, not more.Your deletes should exact match with your allocations. In this case, the only allocation is:
so the only deletion should be:
As far as
friend
functions go, you normally want the friend declaration inside the class definition, but the function definition outside the class definition:There are other possibilities, but that's the general idea. In particular, a friend is never a member function. What you had was a declaration of one (global) function named
show
and a definition of a completely separate member function -- that happened to have the same name, but wasn't really the same function at all.That shows one other point: const-correctness. You were passing the parameter as a reference to Person. Unless it's going to modify the Person object (in which case,
show()
seems like a poor choice of name), it should probably take a reference to a const object. The same general idea applies totake_age()
-- since it only retrieves a value, it should be aconst
function:I've probably already tried to cover too much, so I'll shut up for the moment...
我认为你应该调查你的代码的以下部分(例如,它们下面是什么,这里发生了什么,等等......)
,实际上,等等。我认为,只有当您完成了
基本
内容后,您才能继续进行标题设计问题和友元函数。I think you should investigate the following pieces of your code (like, what's beneath them, what happens here, etc...)
And, actually, so on. Only when you're done with the
basic
stuff, I think, you can move on to header designing questions and friend functions.首先,感谢您尝试找到正确的方法来实施您的课程,特别是在已经错过答案之后。
从您在顶部的描述来看,我认为您可能误解了这项作业的一些要求。首先,我的解释是设置名称和年龄的值应该在 init() 函数中而不是在构造函数中进行。正如其他几位海报所提到的,您的构造函数应该简单地将您的类初始化为已知的良好状态。例如,
然后在初始化函数中,您可以分配值。查看原始的 init() 函数,可能应该提到的是,简单地将指针值 (char *) 分配给另一个指针 (char *) 仅复制指针的值,而不是它表示的数据。因此,对于名称值的分配,您需要计算所需缓冲区的大小,分配缓冲区并自行复制数据。基本的 init() 函数可能看起来像
最后,在析构函数中,您释放类分配的所有资源,在本例中是名称缓冲区。
如果您有一本书或与您的班级相关的东西,您可能需要查看有关指针的信息。它们可能有点棘手,但学习很重要。我怀疑这就是为什么问题指定使用 char * 作为字符串而不是 STL 字符串类。
对于有关将信息放入头文件和源文件中的问题,通常认为创建包含类声明和成员函数原型的头文件,然后在单独的源文件中提供方法的实现是一种很好的做法。对于一些简单的函数,您可以直接在头文件中提供实现。
在单独的源文件中提供类成员定义时,关键是提供类名以正确确定函数的范围(即 Person::)。因此,您的头文件可能包含类似的类定义
,然后在源文件中
使用您的 person 类的源文件只需要包含带有您的类定义的头文件。
First off, kudos on trying to find the right way to implement your class, particularly after having missed the answer already.
From your description at the top, I think you may have misunderstood some of what was being asked for this assignment. First, my interpretation would be that setting the value of the name and age should take place in the init() function rather than in the constructor. As mentioned by several other posters, your constructor should simply initialize your class to a known-good state. For example,
Then in your initialization function, you can assign the values. Looking at your original init() function, it should probably be mentioned that simply assigning a pointer value (char *) to another pointer (char *) only copies the value of the pointer, not the data that it represents. Thus, for the assignment of the name value you need to calculate the size of the buffer you need, allocate the buffer, and copy the data yourself. A basic init() function would probably look like
Finally, in your destructor you free any resources allocated by your class, in this case the name buffer.
If you have a book or something associated with your class, you may want to review the information on pointers. They can be a bit tricky but are important to learn. I suspect that is why the problem specified using char * for strings rather than the STL string class.
To your question about placing information in header and source files, it is often considered good practice to create a header file that contains the class declaration and member function prototypes and then provide the implementation of your methods in a separate source file. For some simple functions, you can provide an implementation directly in your header file.
The key when providing class member definitions in a separate source file is to provide the class name to properly scope the function (i.e., Person::). So your header file may contain a class definition like
And then in your source file
Source files that use your person class need only include the header file with your class definition.
我认为你的问题在于这一行:
朋友 void(Person &p);
需要它做什么呢。
I think your problem is with this line:
friend void(Person &p);
What is it needed for.
除了之前发布的答案之外,我还有两点建议给您:
in addition to the previously posted answers, i've got two points of advice for you: