How to access private data members outside the cla

2019-01-09 06:56发布

This question already has an answer here:

I have a class A as mentioned below:-

class A{
     int iData;
};

I neither want to create member function nor inherit the above class A nor change the specifier of iData.

My doubts:-

  • How to access iData of an object say obj1 which is an instance of class A?
  • How to change or manipulate the iData of an object obj1?

Note: Don't use friend.

12条回答
地球回转人心会变
2楼-- · 2019-01-09 07:00

You can't. That member is private, it's not visible outside the class. That's the whole point of the public/protected/private modifiers.

(You could probably use dirty pointer tricks though, but my guess is that you'd enter undefined behavior territory pretty fast.)

查看更多
在下西门庆
3楼-- · 2019-01-09 07:06

iData is a private member of the class. Now, the word private have a very definite meaning, in C++ as well as in real life. It means you can't touch it. It's not a recommendation, it's the law. If you don't change the class declaration, you are not allowed to manipulate that member in any way, shape or form.

查看更多
看我几分像从前
4楼-- · 2019-01-09 07:07

Here's a way, not recommended though

class Weak {
private:
    string name;

public:
    void setName(const string& name) {
        this->name = name;
    }

    string getName()const {
        return this->name;
    }

};

struct Hacker {
    string name;
};

int main(int argc, char** argv) {

    Weak w;
    w.setName("Jon");
    cout << w.getName() << endl;
    Hacker *hackit = reinterpret_cast<Hacker *>(&w);
    hackit->name = "Jack";
    cout << w.getName() << endl;

}
查看更多
聊天终结者
5楼-- · 2019-01-09 07:11

It's possible to access the private data of class directly in main and other's function...

here is a small code...

class GIFT
{
    int i,j,k;

public:
    void Fun() 
    {
        cout<< i<<" "<< j<<" "<< k;
    }

};

int main()
{
     GIFT *obj=new GIFT(); // the value of i,j,k is 0
     int *ptr=(int *)obj;
     *ptr=10;
     cout<<*ptr;      // you also print value of I
     ptr++;
     *ptr=15;
     cout<<*ptr;      // you also print value of J
     ptr++;
     *ptr=20; 
     cout<<*ptr;      // you also print value of K
     obj->Fun();
}
查看更多
混吃等死
6楼-- · 2019-01-09 07:12

In C++, almost everything is possible! If you have no way to get private data, then you have to hack. Do it only for testing!

class A {
     int iData;
};

int main ()
{
    A a;
    struct ATwin { int pubData; }; // define a twin class with public members
    reinterpret_cast<ATwin*>( &a )->pubData = 42; // set or get value

    return 0;
}
查看更多
虎瘦雄心在
7楼-- · 2019-01-09 07:15

friend is your friend.

class A{
    friend void foo(A arg);
    int iData;
};

void foo(A arg){
     // can access a.iData here
}

If you're doing this regularly you should probably reconsider your design though.

查看更多
登录 后发表回答