2017-04-05 3 views
-2
class foo{ 
    protected: 
    int *data; 
    public: 
    int& operator[](int i); 
    int operator[](int i)const; 
}; 

class goo : public foo{ 

    int& operator[](int i) 
    { 
     foo::operator[](i); 
    } 

    int operator[](int i) const 
    { 
     foo::operator[](i); 
    } 

}; 

부모 클래스 연산자를 호출하고 싶습니다.어떻게 부모 클래스 differnet 연산자를 호출 할 수

int& operator[](int i) 

int operator[](int i) 

하지만은 한 부모의 운영자 int& operator[](int i)가 호출됩니다. 어떻게 수정해야합니까 ??

+1

이 확인'INT 연산자 []'goo' const를'너무 (내가 INT). – songyuanyao

+1

심지어 컴파일합니까? 반환 유형에만 과부하를 적용 할 수 없습니다. – LogicStuff

+0

@songyuanyao 코드를 업데이트했습니다. –

답변

1

당신은 정말 끈적 거리는 클래스에서 두 번째 연산자에서 CONST를 건너 :

#include <iostream> 

using namespace std; 

class foo{ 
    public: 
    int& operator[](int i){ std::cout << "foo[] const" << std::endl; }; 
    int operator[](int i)const { std::cout << "foo[]" << std::endl; }; 
}; 

struct goo : public foo{ 

    int& operator[](int i) 
    { 
     foo::operator[](i); 
    } 

    int operator[](int i) const 
    { 
     foo::operator[](i); 
    } 

}; 

int main() 
{ 
    goo g; 
    g[1]; 
    const goo cg; 
    cg[1]; 

    return 0; 
} 
sh-4.2$ main                                     
foo[] const                                     
foo[] 
+0

의'const_cast' 클래스 뒤에? 왜? 여기에'static_cast' 만 필요합니다. – Quentin

+0

파생 클래스의 두 연산자가 모두 원래가 아닌 오류가있었습니다. – oklas

관련 문제