复制int *数组

时间:2016-10-09 07:29:44

标签: c++ arrays

我必须为我的对象创建一个复制构造函数,它看起来像这样;

class DTable {
private:
    std::string s_name;
    int* *array;
    int size;

public:
    DTable();
    DTable(std::string sName);
    DTable(DTable &pcOther);
    ~DTable();

    void vSetName(std::string sName);
    std::string info();
    int getValue(int index, bool &ok);
    bool setValue(int index, int val);

    const int defaultArrSize = 10;
    const std::string defaultArrName = "Default Name";
};

其中数组变量指向int *数组。复制构造函数我提出了这样的看法;

DTable::DTable(DTable & pcOther) {
    s_name = pcOther.s_name + "_copy";
    size = pcOther.size;
    array = new int*[size];
    for (int i = 0; i < size; i++) {
        array[i] = new int;
        *array[i] = pcOther.*array[i];
    }
}

问题是,我只是无法将指向的int数组的值复制到另一个数组。像这样的解决方案让我有错误

  

表达式必须具有指向成员类型的指针

此外,

array[i] = pcOther.array[i];

是错误的,因为它只是复制引用,因此在更改一个对象后,它的副本也会被更改。我想避免这种情况。

我喜欢为此使用不同的结构,但它必须动态分配int *

的数组

1 个答案:

答案 0 :(得分:0)

您可以使用memcpy(),

DTable::DTable(DTable & pcOther) {
    s_name = pcOther.s_name + "_copy";
    size = pcOther.size;
    array = new int*[size];
    for (int i = 0; i < size; i++) {
        array[i] = new int;
        *array[i] = *(pcOther.array[i]);
        // or
        memcpy ( array[i], pcOther.array[i] , sizeof(int)*1 );
    }
}

Sub OpenFiles(InFile As IO.StreamReader, verifytheFileName As String,dialogBoxTitle As String)
    Dim result As DialogResult
    Dim FilePath As String
    Dim FileName As String

    Try
        dialogBox1.Title = dialogBoxTitle
        dialogBox1.Filter = "Text Files (*.txt)|*.txt|All Files (*.*)|*.*" 
        result = dialogBox1.ShowDialog 'Open This Dialog Box
        FilePath = dialogBox1.FileName 'Gets the Path of the file and stores it in File Path Varible
        FileName = dialogBox1.SafeFileName 'Gets the name of the file and stores it in File Name Varible

        If Not FileName = verifytheFileName Then
            MessageBox.Show("Please Select " &verifytheFileName)
            dialogBox1.Reset()
        Else
            InFile = IO.File.OpenText(FilePath)
        End If                  
    Catch ex As Exception
        MessageBox.Show("ERROR")
    End Try

End Sub

例如。

dialogBox1