【问题标题】:can derived class access base class non-static members without object of the base class派生类可以在没有基类对象的情况下访问基类非静态成员
【发布时间】:2022-01-18 04:26:05
【问题描述】:

派生类可以在没有基类对象的情况下访问基类非静态成员

class base
{
public:
    int data;
    void f1()
    {
    
    }
};
class derived : base 
{
public :
     void f()
    {
        base::data = 44; // is this possible
        cout << base::data << endl;
    }
};

为什么下面的显示错误

class base
{
public:
    int data;
    void f1()
    {
    
    }
};
class derived : base 
{
public :
     static void f()
    {
        base::data = 44; // this one shows a error
        cout << base::data << endl;
    }
};

我在任何婚礼上都找不到答案

【问题讨论】:

  • data 是一个 instance 成员变量。在第二个代码 sn-p 中,f 是一个 static 成员函数。静态成员函数中没有活动实例。因此,没有data,因为没有实例。实例与静态成员之间的区别在任何 C++ 语言的补救文本中都有介绍。
  • 如果没有该类的对象,您希望能够访问该类的非静态成员意味着什么?鉴于您了解非静态成员和静态成员之间的区别是什么,您为什么希望第二个版本能够正常工作?
  • base::data = 44; 实际上是this-&gt;base::data = 44;(因为data 不是static)。在static 方法中作为f,你不能使用this

标签: c++ derived-class base-class non-static


【解决方案1】:

在你的第一个例子中

class derived : base 
{
    void f()
    {
        base::data = 44;
    }
};

f() 不是静态的。它适用于derived 的对象,其中包括base 的对象。所以,base::data = 44; 等价于data = 44;,它访问对象的成员。

在第二个例子中

class derived : base 
{
    static void f()
    {
        base::data = 44;
    }
};

函数f() 是静态的,因此它无法访问任何对象。在那里,base::data = 44; 可能意味着base 的静态data 成员。但是因为data 是非静态的,所以表达式格式不正确。

【讨论】:

    猜你喜欢
    • 2017-01-16
    • 2013-12-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-04-21
    • 1970-01-01
    • 1970-01-01
    • 2018-10-05
    相关资源
    最近更新 更多