从静态成员函数访问私有非静态类变量-C ++

问题描述 投票:-3回答:1

是否可以在静态函数中访问私有非静态变量/方法?如是,那么“专用”访问修饰符的用途是什么?请通过下面的代码。

// Testclassheader.h file
class TestClass{
private:
int TestVariable;    //Private Variable
int TestFunction();   //Private Method

public:
static void TeststaticFn();   //Static Method

}

void TestClass::TeststaticFn()
{
   TestClass TestObj;
   TestObj.TestVariable = 10; // Compiles perfectly
   TestObj.TestFunction(); //Compiles Perfectly

}

// Another Class
//#include "Testclassheader.h"
class AnotherClass{
public:
int DummyFunc();
}

int AnotherClass::DummyFunc()
{
  TestClass AnotherObj;
  AnotherObj.TestVariable = 15; //Throws Error
  AnotherObj.TestFunction();    //Throws error
}

我在Visual Studio 12中尝试了上面的代码。谁能解释为什么私有变量/方法可以在静态方法中访问(实际上不应该)?

c++ visual-studio oop private static-methods
1个回答
1
投票

是否可以在静态函数中访问私有非静态变量/方法?

是的,私有非静态变量/方法可通过属于同一类的静态函数访问。

如果是,那么“专用”访问修饰符的用途是什么?

它防止其他类访问该类的私有类成员和私有实例成员。

谁能解释为什么私有变量/方法可以通过静态方法访问?

因为类的所有部分都是该类的一部分。

实际上哪个[私有变量/方法]不应该[可用于同一类的静态方法])?

不正确。


0
投票
给定类的

所有功能可以访问该类的private成员。您似乎认为private限制了对该特定实例的成员函数的访问,这是不正确的。

class foo
  {
  // access of the function doesn't matter, but let's use public
  public: 

  // the only case you thought was legal:
  void bar()
    {
    baz = 1;
    }

  // but this is perfectly legal
  void qux(foo otherFoo)
    {
    otherFoo.baz = 1;
    }

  // also legal, as you discovered.
  static void quux(foo iPittyTheFoo)
    {
    iPittyTheFoo.baz = 1;
    }

  private:
  int baz;
  };

  class someOtherClass
    {
    // no function here (static or otherwise) has access to baz.
    };

此外,“ // throws error”具有误导性。 “抛出”专门指异常处理,而不是编译时错误。编译器错误,链接器错误和运行时错误都非常不同,并且需要不同类型的问题解决方案来处理。当从不看实际错误输出的人那里寻求帮助时,您需要指定它是哪个。通常,仅复制粘贴错误本身是一个好主意,然后我们所有人都有相同的信息。

© www.soinside.com 2019 - 2024. All rights reserved.