2011-11-29 2 views
3

C++로 응용 프로그램을 만들려고합니다. 응용 프로그램에서 기본 생성자와 3 개의 인수가있는 다른 생성자가 있습니다. 사용자는 키보드에서 기본이 아닌 생성자를 사용하여 객체 배열을 만드는 데 사용할 정수를 제공합니다. 불행히도 나는 지금까지 그것을 끝낼 수 없었습니다. 왜냐하면 저는 기본이 아닌 생성자를 사용할 객체의 배열 생성에 문제가 있기 때문입니다. 제안이나 도움이 필요하십니까? 내가 cin 걸릴 것C++에서 생성자 및 객체 배열

#include<iostream> 
#include<cstring> 
#include<cstdlib> 
#include <sstream> 

using namespace std; 

class Station{ 

public: 
    Station(); 
    Station(int c, char *ad, float a[]);  
    ~Station(); 


    void setAddress(char * addr){ 

     char* a; 
     a = (char *)(malloc(sizeof(addr+1))); 
     strcpy(a,addr); 
     this->address = a; 
    } 

    void setCode(int c){ 
     code=c; 
    } 

    char getAddress(){ 
     return *address; 
    } 

    int getCode(){ 
     return code; 
    } 


    float getTotalAmount(){ 
     float totalAmount=0; 
     for(int i=0;i<4;i++){ 
      totalAmount+=amount[i]; 
     } 
     return totalAmount; 
    } 

    void print(){ 

     cout<<"Code:"<<code<<endl; 
     cout<<"Address:"<<address<<endl; 
     cout<<"Total Amount:"<<getTotalAmount()<<endl; 
     cout<<endl; 
    } 


private: 
    int code; 
    char *address; 
    float amount[4]; 

}; 


Station::Station(){ 
    code= 1; 
    setAddress("NO ADDRESS GIVEN"); 
    amount[0]= 0.0; 
    amount[1]= 0.0; 
    amount[2]= 0.0; 
    amount[3]= 0.0; 

} 


Station::Station(int c, char *ad, float a[]){ 

    if((c>=1&& c<=10)){ 
     code=c; 
     address=ad; 

     for(int i=0;i<4;i++){ 
      amount[i]=a[i]; 
     } 

    }else{ 

     code= 1; 

     setAddress("NO ADDRESS GIVEN"); 
     amount[0]= 0.0; 
     amount[1]= 0.0; 
     amount[2]= 0.0; 
     amount[3]= 0.0; 
    } 
} 


Station::~Station(){ 

} 

int main(){ 

    int size,code; 
    char *addrr; 
    addrr = (char *)(malloc(sizeof(addrr+1))); 
    float mes[4]; 

    do{ 
     cout<<"size of array:"; 
     cin>>size; 

    }while(size<=0 || size>=11); 

    // Station *stations= new Station[size]; 
    // Station** stations = new Station*[size]; 
    Station stations[size]; 

    for(int i=0;i<size;i++){ 

     cout<<"code:"; 
     cin>>code; 

     cout<<"address:"; 
     cin>>addrr; 

     double amo=0; 

     for(int k=0;k<4;k++){ 
      cout<<"values"<<k+1<<":"; 
      cin>>mes[k]; 
     } 
    } 
    /* 
    for(int q=0;q<size;q++){ 
     stations[q].print(); 
    } 
    */ 

    return 0; 
} 

값이 나는 배열의 객체에 할당 할!

+0

이 우리에게 코드를 제공 ... –

+1

HTTP : //mattgemmell.com/2008/12/08/what-have-you-tried/ – FailedDev

+0

배열 생성을 보여 주시겠습니까? new 또는 malloc을 사용합니까? – LostMohican

답변

11

당신은 할 수 있습니다 기본 초기화 배열을 만든 다음 원하는 객체 배열 입력 :

foo arr[10]; 
std::fill(arr, arr+10, foo(some, params)); 

는 다른 방법이 std::vector 사용할 수를 그냥 수행

std::vector<foo> arr(10, foo(some, params)); 
2

를 C++에서 0x이면 새 표현식에 braced-init-list을 사용할 수 있습니다. 즉, 다음을 할 수 있습니다.

#include <iostream> 

class A 
{ 
public: 
    A(int i, int j){std::cout<<i<<" "<<j<<'\n';} 
}; 

int main(int argc, char ** argv) 
{ 
    int *n = new int[3]{1,2,3}; 
    A *a = new A[3]{{1,2},{3,4},{5,6}}; 
    delete[] a; 
    delete[] n; 
    return 0; 
} 

g ++ 4.5.2에서 컴파일 g++ -Wall -std=c++0x -pedantic

0

std::string을 사용할 수 없다고 했으므로이 작업은 훨씬 어려울 것입니다. addrr = (char *)(malloc(sizeof(addrr+1))); 줄은 당신이 생각하는대로하지 않습니다. 힙에 할당하기 위해 malloc을 사용하는 대신에 free (메모리 누수로 연결됨)이 없으므로 미리 결정된 버퍼 크기 (char addrr[BUFFER_LENGTH])로 스택에 할당하는 것이 훨씬 쉽습니다. Station의 선언 전에 const int BUFFER_LENGTH = 20; 또는 다른 적절한 길이로 정의 된 BUFFER_LENGTH으로 정의하십시오.

기본값이 아닌 생성자를 사용하려면 for 루프의 끝에 stations[i] = Station(c, addrr, mes);을 추가하면됩니다.

for(int i=0;i<size;i++){ 
    cout<<"code:"; 
    cin>>code; 

    cout<<"address:"; 
    cin>>addrr; // do not read in strings longer than 20 characters or increase BUFFER_LENGTH’s size 

    double amo=0; 

    for(int k=0;k<4;k++){ 
     cout<<"values"<<k+1<<":"; 
     cin>>mes[k]; 
    } 

    stations[i] = Station(c, addrr, mes); 
} 

그러나

,이 생성자는 addrr 포인터가 아닌 데이터를 복사하기 때문에 제대로 작동하지 않을. 데이터 멤버 char *addresschar address[BUFFER_LENGTH]으로 변경하는 것도 좋습니다. 그런 다음 생성자에서 address=ad;strcpy(address, ad);으로 바꿀 수 있습니다.

참고 : setAddressgetAddress은 이제 업데이트해야합니다.

또 다른 문제는 Station stations[size];입니다. size은 컴파일 타임에 알려지지 않았기 때문에 이것은 비표준입니다. 어느 Station *stations= new Station[size];를 사용하고 delete에 기억하거나 당신이 std::vector를 사용할 수있는 경우가 std::vector 길을 갈 경우, std::vector<Station> stations(size);

를 사용 push_back를 사용하여 잘 작동합니다

std::vector<Station> stations; 

for(int i=0;i<size;i++){ 

    cout<<"code:"; 
    cin>>code; 

    cout<<"address:"; 
    cin>>addrr; 

    double amo=0; 

    for(int k=0;k<4;k++){ 
     cout<<"values"<<k+1<<":"; 
     cin>>mes[k]; 
    } 

    stations.push_back(Station(c, addrr, mes)); 
}