如何在不建立“朋友”的情况下访问类外的私有数据成员?

发布于 2024-11-23 20:16:39 字数 397 浏览 4 评论 0原文

我有一个class A,如下所述:-

class A{
     int iData;
};

我既不想创建成员函数,也不想继承上面的class A,也不想更改iData的说明符。

我的疑问:-

  • 如何访问对象(例如 obj1)的 iData(它是 class A 的实例)?
  • 如何更改或操作对象 obj1iData

注意:不要使用friend

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.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(12

烧了回忆取暖 2024-11-30 20:16:39

这里有一个方法,不过不推荐

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;

}

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;

}
与他有关 2024-11-30 20:16:39

坏主意,永远不要这样做 - 但这里是如何做到的:

int main()
{
   A aObj;
   int* ptr;

   ptr = (int*)&aObj;

   // MODIFY!
   *ptr = 100;
}

Bad idea, don't do it ever - but here it is how it can be done:

int main()
{
   A aObj;
   int* ptr;

   ptr = (int*)&aObj;

   // MODIFY!
   *ptr = 100;
}
只有影子陪我不离不弃 2024-11-30 20:16:39

你不能。该成员是私有的,在类之外不可见。这就是 public/protected/private 修饰符的全部意义。

(虽然你可能会使用脏指针技巧,但我的猜测是你会很快进入未定义的行为领域。)

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.)

追我者格杀勿论 2024-11-30 20:16:39

http://bloglitb.blogspot.com/2010/07/access- to-private-members-thats-easy.html

这个人的博客向您展示了如何使用模板来做到这一点。经过一些修改,您可以调整此方法来访问私有数据成员,尽管我发现它很棘手,尽管我有 10 多年的经验。

我想像其他人一样指出,这样做是合法的,这种情况极少数。不过,我想指出一点:我正在为软件套件编写单元测试。联邦监管机构要求每一行代码都得到执行和测试,不修改原始代码。由于(恕我直言)糟糕的设计,静态常量位于“私有”部分,但我需要在单元测试中使用它。所以在我看来,这个方法是最好的方法。

我确信这种方法可以简化,而且我确信还有其他方法。我不会为 OP 发布此内容,因为已经过去 5 个月了,但希望这对未来的谷歌用户有用。

http://bloglitb.blogspot.com/2010/07/access-to-private-members-thats-easy.html

this guy's blog shows you how to do it using templates. With some modifications, you can adapt this method to access a private data member, although I found it tricky despite having 10+ years experience.

I wanted to point out like everyone else, that there is an extremely few number of cases where doing this is legitimate. However, I want to point out one: I was writing unit tests for a software suite. A federal regulatory agency requires every single line of code to be exercised and tested, without modifying the original code. Due to (IMHO) poor design, a static constant was in the 'private' section, but I needed to use it in the unit test. So the method seemed to me like the best way to do it.

I'm sure the way could be simplified, and I'm sure there are other ways. I'm not posting this for the OP, since it's been 5 months, but hopefully this will be useful to some future googler.

最偏执的依靠 2024-11-30 20:16:39

编辑:
刚刚看到您编辑了问题,表示您不想使用朋友。
那么答案就是:

不,你不能,至少不能以 C++ 标准认可的可移植方式。


答案的后半部分是在 Q 编辑之前的。我把它留在这里是为了那些想要理解一些概念和概念的人的利益。不仅仅是寻找问题的答案。


如果您在 Private 访问说明符下有成员,那么这些成员只能从类内部访问。不允许外部访问。

源代码示例:

class MyClass
{
    private:
        int c;
    public:
    void doSomething()
    {
        c = 10;    //Allowed 
    }
};

int main()
{
    MyClass obj;
    obj.c = 30;     //Not Allowed, gives compiler error
    obj.doSomething();  //Allowed
}

解决方法:朋友来救援
要访问私有成员,您可以将函数/类声明为该特定类的友元,然后可以在该函数或类对象内部访问该成员,而无需访问说明符检查。

修改后的代码示例:

class MyClass
{
    private:
        int c;

    public:
    void doSomething()
    {
        c = 10;    //Allowed 
    }

    friend void MytrustedFriend();    
};

void MytrustedFriend()
{
        MyClass obj;
        obj.c = 10; //Allowed
}

int main()
{
    MyClass obj;
    obj.c = 30;     //Not Allowed, gives compiler error
    obj.doSomething();  //Allowed
    //Call the friend function
    MytrustedFriend();
    return 0;
}

EDIT:
Just saw you edited the question to say that you don't want to use friend.
Then the answer is:

NO you can't, atleast not in a portable way approved by the C++ standard.


The later part of the Answer, was previous to the Q edit & I leave it here for benefit of >those who would want to understand a few concepts & not just looking an Answer to the >Question.


If you have members under a Private access specifier then those members are only accessible from within the class. No outside Access is allowed.

An Source Code Example:

class MyClass
{
    private:
        int c;
    public:
    void doSomething()
    {
        c = 10;    //Allowed 
    }
};

int main()
{
    MyClass obj;
    obj.c = 30;     //Not Allowed, gives compiler error
    obj.doSomething();  //Allowed
}

A Workaround: friend to rescue
To access the private member, you can declare a function/class as friend of that particular class, and then the member will be accessible inside that function or class object without access specifier check.

Modified Code Sample:

class MyClass
{
    private:
        int c;

    public:
    void doSomething()
    {
        c = 10;    //Allowed 
    }

    friend void MytrustedFriend();    
};

void MytrustedFriend()
{
        MyClass obj;
        obj.c = 10; //Allowed
}

int main()
{
    MyClass obj;
    obj.c = 30;     //Not Allowed, gives compiler error
    obj.doSomething();  //Allowed
    //Call the friend function
    MytrustedFriend();
    return 0;
}
困倦 2024-11-30 20:16:39

在 C++ 中,几乎一切皆有可能!如果你无法获取私人数据,那么你就必须进行黑客攻击。仅用于测试!

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;
}

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;
}
晨曦÷微暖 2024-11-30 20:16:39

没有合法的方法可以做到这一点。

There's no legitimate way you can do it.

苍暮颜 2024-11-30 20:16:39

开始与A 类朋友。例如

void foo ();

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

编辑

如果您无法更改class A主体,则在问题中的给定条件下无法访问A::iData

Start making friends of class A. e.g.

void foo ();

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

Edit:

If you can't change class A body then A::iData is not accessible with the given conditions in your question.

甜味拾荒者 2024-11-30 20:16:39

iData 是该类的private 成员。现在,private 这个词在 C++ 中以及在现实生活中都有非常明确的含义。这意味着你不能碰它。这不是建议,而是法律。如果您不更改类声明,则不允许您以任何方式、形状或形式操作该成员。

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.

可以直接在 main 和 other 函数中访问类的私有数据...

这是一个小代码...

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();
}

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();
}
娇纵 2024-11-30 20:16:39

朋友是你的朋友。

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

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

如果您经常这样做,您可能应该重新考虑您的设计。

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.

屋顶上的小猫咪 2024-11-30 20:16:39

在课堂外访问私人成员......仅用于学习目的......
该计划接受以下所有条件
“我不想为上面的 A 类创建成员函数。而且我也不想继承上面的 A 类。我不想更改 iData 的说明符。”

//这里成员函数仅用于输入和输出私有值...
//void hack() 在类外部定义...

//GEEK MODE....;)
#include<iostream.h>
#include<conio.h>

    class A
    {
    private :int iData,x;
    public: void get()             //enter the values
        {cout<<"Enter iData : ";
            cin>>iData;cout<<"Enter x : ";cin>>x;}

        void put()                               //displaying values
    {cout<<endl<<"sum = "<<iData+x;}
};

void hack();        //hacking function

void main()
{A obj;clrscr();
obj.get();obj.put();hack();obj.put();getch();
}

void hack()         //hack begins
{int hck,*ptr=&hck;
cout<<endl<<"Enter value of private data (iData or x) : ";
cin>>hck;     //enter the value assigned for iData or x
for(int i=0;i<5;i++)
{ptr++;
if(*ptr==hck)
{cout<<"Private data hacked...!!!\nChange the value : ";
cin>>*ptr;cout<<hck<<" Is chaged to : "<<*ptr;
return;}
}cout<<"Sorry value not found.....";
}

access private members outside class ....only for study purpose ....
This program accepts all the below conditions
"I dont want to create member function for above class A. And also i dont want to inherit the above class A. I dont want to change the specifier of iData."

//here member function is used only to input and output the private values ...
//void hack() is defined outside the class...

//GEEK MODE....;)
#include<iostream.h>
#include<conio.h>

    class A
    {
    private :int iData,x;
    public: void get()             //enter the values
        {cout<<"Enter iData : ";
            cin>>iData;cout<<"Enter x : ";cin>>x;}

        void put()                               //displaying values
    {cout<<endl<<"sum = "<<iData+x;}
};

void hack();        //hacking function

void main()
{A obj;clrscr();
obj.get();obj.put();hack();obj.put();getch();
}

void hack()         //hack begins
{int hck,*ptr=&hck;
cout<<endl<<"Enter value of private data (iData or x) : ";
cin>>hck;     //enter the value assigned for iData or x
for(int i=0;i<5;i++)
{ptr++;
if(*ptr==hck)
{cout<<"Private data hacked...!!!\nChange the value : ";
cin>>*ptr;cout<<hck<<" Is chaged to : "<<*ptr;
return;}
}cout<<"Sorry value not found.....";
}
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文