灵活的可调整大小的数组C ++

时间:2015-01-30 16:48:52

标签: c++ arrays templates

我的任务是创建一个实现安全可调整大小数组的类,它可以 包含任何单一类型的数据。

  • 使用模板,以便存储在数组中的数据可以是任何类型。

  • 提供将数组设置为的“default”(无参数)构造函数 一些合理的默认初始大小。

  • 为另一个构造函数提供一个允许的int参数 程序员指定原始大小。

    template<typename stuff> //my template
    class safearray
    {
    public:
    int size;
    stuff*data[size];
    
    safearray def_size() // default size constructor
        {int size = 0; return size;}
    
    
    safearray new_size(new_int) 
        {delete [] data;
         data = new int [newsize]; 
         size = newsize; }
    

大多数情况下,我想知道我是否在正确的轨道上,我是编程的新手,所以我不确定所有语法是否正确。任何帮助都是apreciated

1 个答案:

答案 0 :(得分:3)

嗯,首先,使用正确的命名和一些约定可能是个好主意:

  • stuff模板参数并没有真正告诉用户它在做什么。考虑使用ElementTElement之类的内容。如果您没有创造性的情绪,请T
  • safearray不太清晰,考虑使用可以帮助读者区分单词的内容,例如safe_arraySafeArray

然后,做一些缩进会很好。你可以做到

void SomeMethod() {
    // code here
}

void SomeMethod()
{
    // code here
}

接下来,你对什么是构造函数的想法是错误的。基本思想是构造函数是一个没有返回类型且与包含类同名的方法,例如。

class SomeClass
{
private:  // private marks the internal state of the class
          // it is inaccessible from the outside of the class
    int someValue;
    // it might be a good idea to store the size of the array here
    // so the user cannot modify the size

public:
    SomeClass()
    {
        someValue = 0;
    }

    SomeClass(int value)
    {
        someValue = value;
    }
};

然后你显然使用类型:

来调用构造函数
void SomeMethod()
{
    SomeClass cl1; // creates an instance of SomeClass on stack calling the
                   // parameter-less constructor

    SomeClass cl2(7); // creates an instance of SomeClass on stack with
                      // the parametrized constructor

    SomeClass* cl3 = new SomeClass(12); // creates an instance of SomeClass on heap 
                                        // with the parametrized constructor

    delete cl3; // remember to delete everything that has been created with new
}

如果你需要创建某个数组,你可以

size_t size = 6; // your required size comes here, e.g. constructor parameter
int* array = new int[size];

有了模板参数T,你显然需要做

T* array = new T[size];

所以这对于这些东西来说真的是一个快速而不是非常精确的演练。如果我是你,我会在评论中采用推荐的书籍,并从头开始学习。这种级别的任务对你的技能水平来说是疯狂的,并且不会让你对编程或C ++有更深入的理解。

PS。我是学生:)

相关问题