2013-05-21 5 views
0

저는 C++로 이와 같은 작업을하려고합니다. 그냥 원래의 형태로 다시 캐스팅cpp는 포인터 배열에 객체를 저장합니다.

void showContensofArray(void *data[]) 
{ 
     //In this function have to display the values of respective objects. 
     // Any ideas how do I do it? 
} 
int main(){ 
    A phew(xxx,abcdefg); //object of class A 

    B ball(90),ball2(88); //object of class B 

    void *dataArray[2]; 
    dataArray[0] = &ph1; 
    dataArray[1] = &ball; 
    showContentsofArray(dataArray); //function 
} 

답변

0
void showContensofArray(void *data[], int len) 
{ 
    int i; 
    for(i=0;i<len;i++){ 
     ((Base*)(data[i]))->print(); 
    } 
} 

그리고 모든 클래스의 값을 인쇄하는 방법을 알고있는 방법 print()의 구현을 가져야한다.

상속을 사용할 수도 있습니다.

편집 :

Ricibob의 대답은 정확하지만 당신은 함수 내에서 캐스팅을 할 필요가 있다면, 당신은 같은 것을 할 필요가 @ :

#include <iostream> 

using namespace std; 

class Base{ 
public: 
    virtual void print()=0; 
}; 
class A: public Base{ 
public: 

    void print(){ 
     cout<<"Object A"<<endl; 
    } 
}; 

class B: public Base{ 
public: 
    void print(){ 
     cout<<"Object B"<<endl; 
    } 
}; 

void showContensofArray(void* data[], int len) 
{ 
    int i; 
    for(i=0;i<len;i++){ 
     ((Base*)(data[i]))->print(); 
    } 
} 

int main(){ 
    A a; 
    B b; 
    void* v[2]; 
    v[0]= &a; 
    v[1] = &b; 
    showContensofArray(v,2); 
    return 0; 
} 

당신은 상속을 회피 할 수 없다.

+0

나는 이것을 시도했는데, '->'의 왼쪽은 현재 (void *)를 참조하고 있기 때문에 '->'의 왼쪽을 가리켜 야한다는 에러를 준다. 내가 잘못 가고있는 어떤 생각이 들까? –

+0

지금은 어떨까? – eLRuLL

+0

showContentsOfArray는 void가 아닌 기본 클래스 포인터의 배열을 가져야합니다. 일반적으로 C++의 void ptrs를 다룰 필요는 없습니다. void *를 없애고 기본 클래스 ptrs 및 가상 함수로 작업하면 캐스트의 필요성이 제거되고 코드가보다 깨끗 해집니다. 그 변화를 적용하면 기본적으로 내 대답을 얻었습니다. – Ricibob

0

:

A* p1 = static_cast<A*>(data[0]); 
B* p2 = static_cast<B*>(data[1]); 
+0

내가 배열의 내용의 순서를 모르는 경우 어떻게. 수표를 발행 한 다음 캐스팅 할 수있는 방법이 있습니까? Java와 마찬가지로 객체의 클래스 이름을 가져온 다음 다시 입력 할 수 있습니다. 비슷한 것이 있나요? –

+2

이와 비슷한 것을 원한다면 [boost :: variant] (http://www.boost.org/doc/libs/1_53_0/doc/html/variant.html)를 제안 할 수 있습니다. –

1

data []에있는 객체를 일반적으로 (즉, 설명이나 값을 추출하기 위해 공통 함수를 호출하여) 처리하려는 경우 객체에 대한 클래스 hirachy를 정의하고 showContentsofArray 함수는 귀하의 (공통 기본 클래스) 개체 포인터.
이것은 Polymorphism의 교과서 예제입니다.
"다형성을 사용하면 통일 된 인터페이스를 사용하여 다양한 데이터 유형의 값을 처리 할 수 ​​있습니다."
아래 예제에서 BaseObject BaseObject는 uniform 인터페이스를 정의합니다.

class BaseObject { 
    virtual string description() { return "Base object"; } 
    virtual bool bounces() { return false; } 
} 
class B : public BaseObject { 
    string description() { return "Im a B object" } 
    bool bounces() { return true; } 
} 
class A : public BaseObject { 
    string description() { return "Im an A object" } 
} 

void showContensofArray(BaseObject* data[], int size) { 
    for (int i=0; i<size; i++) { 
     cout << data[i]->description(); 
     if (data[i]->bounces()) 
      cout << "I bounce!"; 
    } 
} 

int main() { 
    A phew(xxx,abcdefg); //object of class A 
    B ball(90),ball2(88); //object of class B 

    BaseObject* dataArray[2]; 
    dataArray[0] = &ph1; 
    dataArray[1] = &ball; 
    showContentsofArray(dataArray); 
} 

윌 출력 :

Im an A object 
Im a B object 
I bounce! 
관련 문제