2011-08-02 3 views
2

이것이 가상 함수와 관련이 있다고 확신하지만 어떻게 작동하는지 고심하고 있습니다. 여기C++ 클래스 - 포함 된 클래스에 함수를 전달하려면 어떻게해야합니까?

내 (간체) 상황 :이

대략 어떤 프로그램이 실행 파일 (computer.h) 빈 화면 컴퓨터를 그리는 한 쌍을, 그리고 또 한 쌍 (program.h는) 해당 컴퓨터 화면

컴퓨터 클래스는 다양한 상황에서 재사용 될 것입니다에 그릴 필요로하는 기능 때문에 화면 그리기 기능은 computer.h에 일반적인 패션

에 전달 될 필요가있다 :

include "screen.h" 

class computer { 

    void drawComputer(); //this function draws a picture of a computer 
    void drawMonitor(); 

}; 

computer.cpp에 :

void computer::drawComputer(){ 

    //draws all the components then the monitor 

    drawMonitor(); //this is where the external function (from class screen) needs to execute 
} 

void computer::drawMonitor(){ 
    //draws the background and border of screen 
} 

program.h에서 :

class program { 

    //many other program functions 

    void drawScreen(); 

}; 

program.cpp에서 :

//many other program functions 

void program::drawScreen(){ 
    //this function draws the contents of the screen 
} 

내 질문에 내가 drawScreen() 기능을 '전송'어떻게 program.cpp에서이다내에서 실행의 기능은 computer.cpp에 있습니까? 선이

testApp.h:40: error: 'testApp::prog' cannot appear in a constant-expression 
testApp.h:40: error: `&' cannot appear in a constant-expression 
testApp.h:40: error: a cast to a type other than an integral or enumeration type cannot appear in a constant-expression 
testApp.h:40: error: ISO C++ forbids initialization of member 'isprog' 
testApp.h:40: error: making 'isprog' static 
testApp.h:40: error: invalid in-class initialization of static data member of non-integral type 'IScreen*' 
testApp.h:41: error: 'isprog' has not been declared 
testApp.h:42: error: ISO C++ forbids declaration of 'comp1' with no type 
testApp.h:42: error: expected ';' before '.' token 

있습니다

편집

@ 크리스 '솔루션은 내가 다음과 같은 오류 얻을 그것을 구현하려고하지만 때, 거의 정확히 내가 후에 누구인지 것 같다

39 Program prog; 
40 IScreen *isprog = dynamic_cast<IScreen*>(&prog); 
41 OP1 comp1(isprog); 
42 comp1.drawScreen(); 

어디에서 구현이 잘못 될지 알고 계신가요?

답변

3

그럼 반 길입니다. 이런 식으로, 나는 추상적 인 인터페이스를 정의하기 위해 가상 함수를 사용할 것이다.여기에 내가 그것을 할 거라고 방법의 기본 개요입니다 :

// First create a class to define an interface for drawing a screen 
class IScreen 
{ 
public: 
    // Defines an interface named drawScreen 
    virtual void drawScreen() = 0; 
}; 

// Next actually implement the interface 
class Program : public IScreen 
{ 
public: 
    // Here we actually implement it 
    virtual void drawScreen() 
    { 
     // Draw some stuff here 
    } 
}; 

// You can implement this more than once if you want 
class BlueScreenOfDeathScreen : public IScreen 
{ 
public: 
    virtual void drawScreen() 
    { 
     // Draw a BSOD on the screen 
    } 
}; 

// Finally, use the interface 
class Computer 
{ 
private: 
    IScreen* myScreen; 

public: 
    Computer(IScreen* screen) 
     : myScreen(screen) 
    { 
    } 

    void drawComputer() 
    { 
     // ... 
    } 

    void drawMonitor() 
    { 
     // Draw the monitor 
     // ... 

     // Draw the screen 
     myScreen->drawScreen(); 
    } 
}; 

이런 식으로 이렇게, 당신은 쉽게 여러 IScreen 구현을 정의하고 신속하게 코드에 대한 최소한의 변경으로 그들을 교환합니다.

// Render using the "Program" class 
Program prog; 
IScreen *iprog = dynamic_cast<IScreen*>(&prog); 
Computer comp1(iprog); 
comp1.drawScreen(); 

// Render using the "BlueScreenOfDeathScreen" class 
BlueScreenOfDeathScreen bsod; 
IScreen *ibsod = dynamic_cast<IScreen*>(&bsod); 
Computer comp2(ibsod); 
comp2.drawScreen(); 

쉽지 않으십니까?

+0

고마워요. @ 크리스, 내가 뭘하고있는 것처럼 보이는 것. 내 '프로그램'클래스가 이미 다른 클래스를 상속하고있어 '추상적 인 유형의 객체를 할당 할 수 없습니다'라는 오류가 발생했습니다. 'testApp'오류 –

+0

그 문제를 해결했습니다. - 구현하지 못했습니다. . 이제는 잘 컴파일되지만,'myScreen-> drawScreen();과'EXEC_BAD_ACCESS' 에러로 충돌합니다. 잘못된 메모리 덩어리에 접근하는 것과 관련된 에러입니다. 어떤 아이디어? –

+0

관련 코드 조각 ('Program' 할당 방법 포함) 없이는 주석을 달 수 없습니다. 한 가지 가능성은 'myScreen'이 가리키고있는 것은 삭제되었지만 (어둠 속에서는 완전히 찌르는 것입니다.) –

1

당신과 같이 컴퓨터 클래스에 program의 인스턴스를 생성해야 할 것 :

Program mypgm; 

을 다음

void computer::drawMonitor(){ 
    //draws the background and border of screen 
    mypgm.DrawScreen(); 

} 
+0

예, 가능하다는 것을 알았지 만 문제는 컴퓨터 클래스가 프로그램 클래스에 의해서만 호출되지 않기 때문입니다. 다른 클래스가 될 수 있습니다. 더 일반적인 구현이 있습니까? –

0

가장 정직하고 대답 내에서 객체를하는 것입니다 program 안에 computer을 입력하고 내부에서 drawScreen()을 호출하십시오. 즉

class computer { 
    program prg; // <--- internal object 
//... 
}; 
void computer::drawMonitor() { 
    prg.drawScreen(); 
} 

다른 방법으로 drawMonitorprogram의 목표물을 통과하는 방법을 호출한다. 즉

void computer::drawMonitor(program &prg) { // <--- pass by reference 
    prg.drawScreen(); 
} 
관련 문제