이것이 가상 함수와 관련이 있다고 확신하지만 어떻게 작동하는지 고심하고 있습니다. 여기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();
어디에서 구현이 잘못 될지 알고 계신가요?
고마워요. @ 크리스, 내가 뭘하고있는 것처럼 보이는 것. 내 '프로그램'클래스가 이미 다른 클래스를 상속하고있어 '추상적 인 유형의 객체를 할당 할 수 없습니다'라는 오류가 발생했습니다. 'testApp'오류 –
그 문제를 해결했습니다. - 구현하지 못했습니다. . 이제는 잘 컴파일되지만,'myScreen-> drawScreen();과'EXEC_BAD_ACCESS' 에러로 충돌합니다. 잘못된 메모리 덩어리에 접근하는 것과 관련된 에러입니다. 어떤 아이디어? –
관련 코드 조각 ('Program' 할당 방법 포함) 없이는 주석을 달 수 없습니다. 한 가지 가능성은 'myScreen'이 가리키고있는 것은 삭제되었지만 (어둠 속에서는 완전히 찌르는 것입니다.) –