아래 코드를 확인하십시오. 클래스 A의 개인 데이터 멤버의 수정을 제한하는 해결책이 필요합니다. 제안하십시오.C++에서 개체의 개인 데이터 멤버 수정을 제한하는 방법?
class A{
private:
int a;
int b;
public:
A(int i=0, int j=0):a(i),b(j){
cout<<"A's constructor runs"<<endl;
}
void showVal(){
cout<<"a: "<<a<<" b: "<<b<<endl;
}
};
int main(){
A ob1(10,20);
ob1.showVal();
int *ptr = (int*)&ob1;
*(ptr+0)=1;
*(ptr+1)=2;
ob1.showVal();
return 0;
}
여기에 문제가 없습니다. 프로그램에 정의되지 않은 동작이 있습니다. –
멤버 변수에 액세스하는 것과 같은 오프셋을 가정 할 수는 없습니다. [오프셋을 결정하는 방법] (https://stackoverflow.com/questions/13180842/how-to-calculate-offset-of-a-class-member-at-compile-time)이 있지만 간단히 가정 할 수는 없습니다. 패딩, vtable 등으로 인한 가치. [here] (https://stackoverflow.com/questions/12378271/what-does-an-object-look-like-in-memory) – CoryKramer