const
은 입니다.은 변수를 변경하지 않을 것을 약속합니다. 그것은 여전히 바뀔 수 있습니다. a
을 변경할 수 있습니다
class A {
public:
A(const int& a);
int getValue() const;
void setValue(int b);
private:
const int& a;
};
A::A(a) : a(a) {}
int A::getValue() const {
return a;
}
void A::setValue(int b) {
a = b; // error
}
int main() {
int my_a = 0;
A a(my_a);
std::cout << a.getValue() << std::endl; // prints 0
my_a = 42;
std::cout << a.getValue() << std::endl; // prints 42
}
어떤 방법 없다 A::*
하지만 main
캔. 그 정도는 C와 C++간에 동일합니다. 이 무엇 C++
부적절 const
을 폐기에서 프로그래머를 억제 해야하는 const
을 우회하는 커플 (제한) 방법이다.
이 같은 수업을 듣습니다.
class A {
public:
A();
int getValue();
private:
static int expensiveComputation();
int cachedComputation;
};
A::A() : cachedComputation(0) {}
A::getValue() {
if (cachedComputation == 0)
cachedComputation = expensiveComputation();
return cachedComputation;
}
cachedComputation
암시 this->cachedComputation
을 의미한다. 이를 명심하십시오. 비 const
메소드가 호출 const A a2
중이므로
int main() {
A a1;
const A a2;
std::cout << a1.getValue() << std::endl;
std::cout << a2.getValue() << std::endl; // error
}
a2.getValue()
불법이다. 컴파일러는 다른, 단지 const
-ness가 주조되고 있다는 것도 확인 없기 때문에 하나는
std::cout << ((A&)a2).getValue() << std::endl; // C-style cast
std::cout << const_cast<A&>(a2).getValue() << std::endl; // C++-style cast
두 번째
선호합니다 ...
const
-ness을 멀리 캐스팅 할 수있다. 그러나 이것은 여전히 이상적이지 않습니다. 대신 클래스에 새로운 메소드가 추가되어야합니다.
class A {
public:
int getValue() const;
};
A::getValue() const {
if (cachedComputation == 0)
cachedComputation = expensiveComputation(); // error
return cachedComputation;
}
지금 너무 a2.getValue()
괜찮하는 const
방법이있다. 그러나 후행 const
은 메서드에 포인터가 지정되어 있으며 평소와 마찬가지로 A *this
포인터가 아니므로 this->cachedComputation
은 const int &
이고 변경할 수 없습니다.
const_cast
은 메서드 내부에 적용 할 수 있지만이 멤버의 선언을 변경하는 것이 좋습니다. 심지어 const A *this
와 지금
class A {
private:
mutable int cachedComputation;
};
는
this->cachedComputation
캐스팅없이 변이 될 수있다.
http : // stackoverflow.com/questions/455518/how-many-of-the-use-of-const-in-c – karlphillip
@karlphillip : 답변이 아닙니다. 이것은 C++에서 const를 사용하는 것을 나열하지만 C와 C++ 사이의 const 차이점을 나열하지 않습니다. 완전히 다른. –
답변이 있어야한다면 그렇게 게시 할 것입니다. – karlphillip