C ++对象的构造函数 [英] Constructors for C++ objects

查看:156
本文介绍了C ++对象的构造函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有类Person,如下:

  class Person {
char * name;
int age
};

现在我需要添加两个造型。一个不带参数,将字段值插入动态分配的资源。第二次取(char *,int)由初始化列表初始化的参数。最后一部分是定义一个析构函数,显示有关销毁对象和解除动态分配资源的信息。如何执行此任务?



这是我已经有的:

  class Person {
char * name;
int age
public:
Person(){
this-> name = new * char;
this-> age = new int;
}

人(char * c,int i){
}
};


解决方案

在默认构造函数中,char数组的分配包含其所需的大小,例如

  this-> name = new char [32] 

请注意,此大小包括终止的0字符,因此您可以在此存储的名称的有效长度在参数化构造函数中,您可以简单地将给定的参数分配给类成员。



在析构函数中,你需要释放动态分配的资源 - 确保使用 delete [] 当且仅当释放分配给 new []

 〜Person(){
std :: cout< ; 毁坏资源< std :: endl;
delete [] name;
delete age;
}

更新:我错过了这个:想动态分配 age ,您应该声明为 int * age



我假设这个练习的要点是练习动态分配/释放;在这种情况下,它是罚款。然而,一般来说,动态分配 int s并不是好的做法,而应该是 char * 总是使用 std :: string ,它会自动,安全地处理内存分配。


I have class Person as following :

class Person {   
    char* name;
    int age;
};

Now I need to add two contructors. One taking no arguments, that inserts field values to dynamically allocated resources. Second taking (char*, int) arguments initialized by initialization list. Last part is to define a destructor showing information about destroying objects and deallocating dynamically allocated resources. How to perform this task ?

That's what I already have :

class Person {   
    char* name;
    int age;
public:
    Person(){
        this->name = new *char;
        this->age = new int;
    }

    Person(char* c, int i){
    }
};

解决方案

In the default constructor, allocation of the char array should include its desired size, e.g.

this->name = new char[32];

Note that this size includes the terminating 0 character, so the effective length of names you can store in this array is 31.

In the parameterized constructor, you can simply assign the given parameters to your class members.

In the destructor, you need to deallocate dynamically allocated resources - make sure to use delete[] when, and only when, deallocating memory allocated with new[]:

~Person(){
    std::cout << "Destroying resources" << std::endl;
    delete[] name;
    delete age;
}

Update: I missed this one: if you want to allocate age dynamically, you should declare it as int* age.

I assume that the point of this exercise is to practice dynamic allocation/deallocation; in this context, it is fine. However, in general, it is not good practice to dynamically allocate ints, and instead of char* you should almost always use std::string, which handles memory allocation for you automatically and safely.

这篇关于C ++对象的构造函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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