2010-06-15 10 views
0

인수로받은이 포인터를 const로 선언하려고합니다.이 포인터를 매개 변수로 전달하는 방법을 const로 지정하는 방법

static void Class::func(const OtherClass *otherClass) 
{ 
    // use otherClass pointer to read, but not write to it. 
} 

는 다음과 같이 호출되는 :

void OtherClass::func() 
{ 
    Class::func(this); 
} 

내가 CONST가 OtherClass 포인터를 선언 해달라고하면이 사려고 컴파일되지 않습니다, 나는 그것을 변경할 수 있습니다.

감사합니다. 이 잘 컴파일

void Class::func(const OtherClass *otherClass) 
{ 
    // use otherClass pointer to read, but not write to it. 
} 
+0

죄송합니다.이 질문에 대해 사과드립니다. 코드에 오류가 있습니다. 더 이상 대답 할 필요가 없습니다. – Tomas

답변

2

이 같은 정적 클래스 memberv 기능을 정의 할 수 없습니다 내 컴퓨터에서 :

#include <iostream> 

class bar; 

class foo { 
public: 
    static void f(const bar* b) { std::cout << b << '\n'; } 
}; 

class bar { 
public: 
    void f() {foo::f(this);} 
}; 

int main(void) 
{ 
    bar b; 
    b.f(); 
    return 0; 
} 

그럼 어떻게 했어? 그렇지?

0

: 같은 기능은 클래스 선언에서 static으로 선언해야

static void Class::func(const OtherClass *otherClass) 
{ 
    // use otherClass pointer to read, but not write to it. 
} 

다음 함수 정의는 같습니다

1

포인터 또는 가리키는 객체를 변경하지 않으려면 대신 const 참조를 사용하십시오.

void Class::func(const OtherClass& otherClass) 
{ 
    // use otherClass ref for read-only use of OtherClass 
} 
void OtherClass::func() 
{ 
    Class::func(*this); 
} 
관련 문제