2017-11-27 9 views
0

:C++ : 생성자에 배열을 전달하고,이 객체에 저장 나는 C++이 자바 스크립트 코드를 할 싶습니다

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*을 어디에서 건 기억할 수 없습니다. 벡터를 전달할 때이 예에서, 그것은 Example 동적 할당을 사용하는 관련 아니다, 벡터

또한

의 쓸모없는 복사본을 방지하기 위해, 참조를 사용하기에

+3

'std :: vector' 사용 – Amadeus

+2

배열은 포인터로 쇠퇴합니다. 배열을'std :: vector '으로 바꾸면 쉽게 복사 할 수 있습니다. – wally

+2

가능한 경우 자동 저장 기간 (예 : example Example (myArr);) 대신 자동 저장 기간 (예 : myArr);을 사용하는 것이 더 바람직하며 원시 포인터 대신 스마트 포인터를 사용하십시오 – UnholySheep

답변

3
#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(); 
} 

, 나는 좋습니다. vector, array, list, map, 같은 표준 컨테이너의

  • 사용 : 동적 할당을 사용할 때,

    개인 조언을 (스마트 포인터를 사용 이상) 개체를 delete하는 것을 잊지 마세요. ... 복사 및 표준 조작을 단순화합니다.

  • 힘들 수있는 동적 할당 데이터의 수동 관리를 피하기 위해 스마트 포인터를 사용합니다 (귀하의 주요 개체를 삭제하는 것을 잊었으며 귀하는 단지 하나만 가지고있는 것입니다)
다음은

, 원시 배열 버전, 적어도 C++ (11),하지만 난 std::vector 또는 std::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(); 
} 
+0

'21:26 : 오류 : 'Example :: Example (int [4])'에 대한 호출과 일치하는 함수가 없습니다. – Forivin

+0

@Forivin Corrected – Garf365

+0

@Forivin은 벡터없이 게시하고 싶습니다. –

2

을 더 많은 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 
} 
+0

고정 크기 컨테이너를 사용하는 좋은 대안 – Garf365