5

我们可以在 C++ 结构(而不​​是类)中使用访问说明符 -private和- 吗?protected

另外,C 中是否存在访问修饰符?

4

6 回答 6

11

C doesn't have C++style access modifiers. A C struct is just a composite object type containing members of other object types.

In C++, a struct and a class are almost identical; the only difference is that struct members are public by default, and class members are private by default. So this:

struct foo {
private:
    // ...
};

is equivalent to this:

class foo: {
    // ...
};

This has been answered elsewhere.

This implies that the private, public, and protected keywords are equally valid in either a struct definition or a class definition.

As a matter of programming style, on the other hand, if you're going to be using access modifiers, it's probably best to define your type as a class rather than as a struct. Opinions will differ on this, but IMHO the struct keyword should be used for POD (Plain Old Data) types, or for types that could be defined as structs in C.

C++ structs, strictly speaking, are very different from C structs, and are nearly identical to C++ classes. But if I see something defined in C++ as a struct, I expect (or at least prefer) it to be something similar to a C struct.

于 2013-03-25T19:13:16.787 回答
3

在 C++ 中,结构与类相同,唯一的区别是默认作用域是公共的,而私有作用域是类的默认作用域。InC访问说明符不存在,但毕竟你会用它们做什么?

于 2013-03-25T14:46:24.910 回答
2

是的,您可以在 C++ 结构中使用public, protectedin 。private

不,C 中不存在访问修饰符。

class在 C++ 中,和之间的唯一区别struct是 a 的成员class是默认private的,而 a 的成员struct是默认的public。这意味着 C++struct可以具有成员函数、构造函数、重载运算符并使用class.

于 2013-03-25T14:45:49.057 回答
1

struct与c ++中没有太大区别class。默认可见性是公开的而不是私有的。C 不支持这些。

于 2013-03-25T14:46:03.607 回答
0

我们可以在 c++ 的结构中使用访问说明符 - 私有的和受保护的吗?

是的。Astruct是一个类;唯一的区别是如果您未指定默认可访问性( publicforstructprivatefor )。class

C语言也允许使用访问修饰符吗?访问说明符真的存在于 C 中吗?

不,C 没有访问说明符。

于 2013-03-25T14:47:15.050 回答
0

C++ 中astruct和 a的唯一区别是 a的成员是默认的,而 a的成员是默认的。您可以在它们中使用访问说明符,就像您可以在它们中使用其他任何东西一样。classstructpublicclassprivate

C 中没有访问说明符。

于 2013-03-25T14:46:16.160 回答