gpt4 book ai didi

c++ - 如何分配和检索成员变量中的值?

转载 作者:太空宇宙 更新时间:2023-11-04 11:48:15 25 4
gpt4 key购买 nike

我从基类 A 的对象向子类 B 放入/获取值。但是我无法分配或获取该值。我的代码是:

class A
{

};

class B: A
{
string SID;
};

class C: A
{
string Name;
};

class D : A
{
string Name;
};

class E
{
A a;
UINT32 AccessLevel;
};

.......

main()
{
E e;
}

正在使用 e 的对象尝试获取子类 B 的值。

我需要从 B 类获取 SID?

谢谢,

最佳答案

C++11 标准 11/3 说:

Members of a class defined with the keyword class are private by default.

在 11.2/2

In the absence of an access-specifier for a base class [...] private is assumed when the class is defined with the class-key class.

在 11.2/1:

If a class is declared to be a base class for another class using the private access specifier, the public and protected members of the base class are accessible as private members of the derived class.

那是什么意思呢?首先:

class A {};
class B : A {};

这里的A,凭借11.2/2是私有(private)继承的。如果您想继承变量并且只想在派生类中为变量实现 getter/setter,这可能没问题,但这通常被认为是不好的风格。

然而,在您的情况下,如 11/3 所述,您的成员根本不会被继承,因为它们是私有(private)成员:

class A
{
public:
int a; // inherited
protected:
int b; // inherited
private:
int c; // NOT inherited
};

尤其是

class A { int a; };

相当于

class A { private: int a; };

因此,您可以通过将成员设置为publicprotected(参见 11.2/1),使您的成员可以从 派生类中访问:

class A { public: int a; };
class B : A {}; // privately inherits a

并且如果您想让派生类的外部可以访问它,您还必须继承public:

class A { public: int a; };
class B : public A {}; // publicly inherits a

但这不是您通常会做的。将变量设为私有(private)并仅公开这些变量的 getter 和 setter 被认为是更好的风格:

class A
{
public:
int get_a() const { return a_; }
void set_a(int val) { a_ = val; }

private:
int a_;
};

class B : public A {}; // now publicly inherits the getters and setters
// but not a_ itself

关于c++ - 如何分配和检索成员变量中的值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19245771/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com