簡體   English   中英

C ++:將數組傳遞給構造函數並將其保存在this對象中

[英]C++: Passing an array to a constructor and saving it in the this object

我想在C ++中執行以下JavaScript代碼:

class Example {
    constructor(myArr) {
        this.myArr = myArr;
    }
    test() {
        console.log(myArr[0])
    }
}
var myArr = [1,2,3,4]
var example = new Example(myArr)
example.test()
// prints `1`

我的C ++嘗試:

#include <iostream>

class Example {
public:
    int myArr[4];
    Example(int myArr[4]);
    void test(void);
};

Example::Example(int myArr[4]) {
    //this.myArr = myArr;
    this->myArr = myArr;
    //myArr = myArr;
}
void Example::test(void) {
    std::cout << this->myArr[0];
}


int main() {
    int myArr[4] = {1,2,3,4};
    Example *example = new Example(myArr);
    example->test();
}

我真的不明白我在做什么錯。 我嘗試了很多不同的事情,例如使用this->代替this. ,但我總是會出錯。 例如,當前版本給我:

 In constructor 'Example::Example(int*)':
12:17: error: incompatible types in assignment of 'int*' to 'int [4]'

我真的不明白我在做什么錯。 我在代碼中的任何地方都將數組指定為int myArr[4] ,我不記得在任何地方傳遞int*

#include <iostream>
#include <vector>

class Example {
public:
    std::vector<int> myArr;
    Example(const std::vector<int> & myArr);
    void test();
};

Example::Example(const std::vector<int>& myArr) {
    this->myArr = myArr;
}
void Example::test() {
    std::cout << this->myArr[0];
}


int main() {
    std::vector<int> myVec{1,2,3,4};
    Example example1(myVec);

    // Or directly
    Example example2({1, 2, 3, 4});

    // And is you don't have choice and use raw array
    int myArr[4] = { 1, 2, 3, 4 };
    Example example3(std::vector<int>(myArr, myArr + 4));

    example1.test();
    example2.test();
    example3.test();
}

傳遞向量時,建議您使用參考,以避免向量的無用復制

另外,在此示例中,對Example使用動態分配也Example 而且,當您使用動態分配時,請不要忘記delete對象(或者最好使用智能指針)

個人建議:

  • 使用標准容器,例如vectorarraylistmap ,...。它們簡化了復制和標准操作
  • 使用智能指針來避免手動管理動態分配的數據,這可能很困難(在您的情況下,您忘記刪除主對象,而只有一個)

下面是原始數組版本,至少適用於c ++ 11,但我建議使用std::vectorstd::array

#include <iostream>

class Example {
public:
    int * myArr = nullptr;
    std::size_t length = 0;
    Example(const int * const myArr, std::size_t length);
    Example(const Example & old); // To respect rule of 5
    Example(Example && old); // To respect rule of 5
    Example &operator=(const Example &rhs); // To respect rule of 5
    Example &operator=(Example &&rhs); // To respect rule of 5
    ~Example();
    void test();
};

Example::Example(const int * const myArr, std::size_t length) {
    this->myArr = new int[length];
    this->length = length;
    for(std::size_t i = 0; i < length; ++i) {
        this->myArr[i] = myArr[i];
    }
}

// Copy constructor
Example::Example(const Example &old) {
    *this = old;
}

// Move constructor
Example::Example(Example &&old) {
    *this = std::move(old);
}

// Copy assignement operator
Example &Example::operator=(const Example & rhs)
{
    length = rhs.length;
    for(std::size_t i = 0; i < length; ++i) {
        myArr[i] = rhs.myArr[i];
    }
    return *this;
}

// Move assignement operator
Example &Example::operator=(Example &&rhs)
{
    myArr = rhs.myArr;
    length = rhs.length;

    rhs.myArr = nullptr;
    rhs.length = 0;

    return *this;
}

void Example::test() {
    std::cout << this->myArr[0];
}

Example::~Example()
{
    if (myArr != nullptr)
        delete myArr;
}


int main() {
    int myArr[4] = {1,2,3,4};
    Example example1(myArr, 4);

    example1.test();
}

我覺得與您分享一種更面向C ++的方法可能是個好主意:

#include <iostream>
#include <array>                // uses same amount of memory as a standard array
                                // but has a set size unlike std::vector
class Example {
public:
    std::array<int, 4> myArr;
    Example(const std::array<int, 4>& myArr);
    void test(void);
};

Example::Example(const std::array<int, 4>& myArr)
    : myArr{myArr}              // initialize myArr directly using a member 
                                // initializer list.
{}

void Example::test(void) {
    std::cout << myArr[0];      // no need for this-> as it is implicit
}

int main() {
    // prefer brace initialization
    std::array<int, 4> myArr{1, 2, 3, 4};

    Example example{myArr};     // avoid pointer so that delete does not have 
                                // to be called explicitly

    example.test();

    // example and myArr will have their destructors
    // called automatically when they go out of scope 
    // as per RAII
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM