C++ 中的值访问

发布于 2024-09-25 12:28:06 字数 124 浏览 0 评论 0原文

嗨,

我有两个 A 类和 B 类, 这里 A 继承了 B,现在我想从 A 访问 B 中的变量,我在 B 中包含了 A 标头并尝试访问,但在 QObject 中显示一些错误。

是否可以这样访问..请帮忙

HI,

I have two clases A and B,
Here A is inheriting B and now i want to access a variable in B from A, I included A header in B and tried to access but showing some error in QObject.

Is it possible to acces like this.. Please help

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

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

发布评论

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

评论(2

情栀口红 2024-10-02 12:28:06

不确定我是否正确理解了你的问题......

class A {
public:
  int nValueA;
protected:
  int nValueB;
private:
  int nValueC;
};

class B : public A {
public:
    B();
    int x, y, z;
}; 
B::B(): 
x(nValueA), //-->OK
y(nValueB), //-->OK
z(nValueC)  //-->error due to child can't inherit parent's private member
{}

void main(){
  B object;
  object.nValueA = 888; //--> valid
  object.nValueB = 888; //--> error since protected member is not accessible
  object.nValueC = 888; //--> error since private member is not accessible
}

可能的解决方案:

class A {
public:
  int nValueA;
  int nValueB;
  int nValueC;
};

Not sure i get your Q correctly....

class A {
public:
  int nValueA;
protected:
  int nValueB;
private:
  int nValueC;
};

class B : public A {
public:
    B();
    int x, y, z;
}; 
B::B(): 
x(nValueA), //-->OK
y(nValueB), //-->OK
z(nValueC)  //-->error due to child can't inherit parent's private member
{}

void main(){
  B object;
  object.nValueA = 888; //--> valid
  object.nValueB = 888; //--> error since protected member is not accessible
  object.nValueC = 888; //--> error since private member is not accessible
}

Possible solution:

class A {
public:
  int nValueA;
  int nValueB;
  int nValueC;
};
狂之美人 2024-10-02 12:28:06

你的成员变量是私有吗?那么你就不能声明它受保护

Is your member variable private? Then you cannot, declare it protected.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文