2017-05-14 7 views
0

거의 비슷한 클래스와 파생 클래스를 만들었습니다. 유일한 차이점은 파생 클래스에는 2 개의 다른 함수와 3 개의 추가 변수가 있다는 것입니다. 나는 상속 기능을 사용하는 클래스 B에서 호출 된 함수를 원하지만라는 대신 클래스 B의 PrivFunctions으로,이 함수는 내가 약을 생각했습니다파생 클래스의 멤버 함수를 사용하는 기본 클래스에서 함수를 호출합니다.

class A 
{ 
protected: 
double x,y,z; 
Function() { 
*do something using the member variables of class A and the member functions of class A* } 

private: 
double PrivFunction() { 
*take in member variables from A and return a certain value* } 

double PrivFunction2() { 
*take in member variables from A and return a certain value* } 

class B : public A 
{ 
private: 
double a,b,c; 

double PrivFunction() { 
*take in member variables from A,B and return a certain value* } 

double PrivFunction2() { 
*take in member variables from A,B and return a certain value* } 

main() { 
B classb(); 
B.Function() 
} 

자신의 클래스, 클래스 A의 PrivFunctions를 사용 Function()에서 private 함수의 주소를 추가하지만 너무 멀리 가져온 것 같습니다. 나는 간단한 것을 놓치고있는 것처럼 느낀다. 그러나 나는 이것을 깔끔하게하는 법을 알지 못한다.

+0

을 나는 당신이 찾고있는 생각 ['virtual' 멤버 함수 (http://en.cppreference.com/w/cpp/language/virtual) . –

답변

0

당신이해야 할 일은 기본 클래스의 함수를 virtual으로 선언하는 것이다. 이것은 기본 클래스 A에서 정의한 함수 유형이며 하위 클래스에서 다시 정의해야합니다. virtual이라는 함수를 선언하면 올바른 함수가 호출되어 모호하지 않게됩니다.

당신의 코드는 다음과 같이 보일 것이다 :

class A 
{ 
    protected: 
    double x, y, z; 
    //define as virtual 
    virtual Function(){/*do something*/} 

    /* 
    rest of your code 
    */ 
} 
class B: public A 
{ 
    private: 
    double a, b, c 

    public: 
    //redefine your function in the subclass 
    Function(){/*do something else*/} 
    /* 
    rest of your code 
    */ 
} 
int main() 
{ 
    B classb(); 
    //This will now use B's Function 
    classb.Function(); 
}