我们可以在 C++ 结构(而不是类)中使用访问说明符 -private
和- 吗?protected
另外,C 中是否存在访问修饰符?
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 struct
s 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
.
在 C++ 中,结构与类相同,唯一的区别是默认作用域是公共的,而私有作用域是类的默认作用域。InC
访问说明符不存在,但毕竟你会用它们做什么?
是的,您可以在 C++ 结构中使用public
, protected
in 。private
不,C 中不存在访问修饰符。
class
在 C++ 中,和之间的唯一区别struct
是 a 的成员class
是默认private
的,而 a 的成员struct
是默认的public
。这意味着 C++struct
可以具有成员函数、构造函数、重载运算符并使用class
.
struct
与c ++中没有太大区别class
。默认可见性是公开的而不是私有的。C 不支持这些。
我们可以在 c++ 的结构中使用访问说明符 - 私有的和受保护的吗?
是的。Astruct
是一个类;唯一的区别是如果您未指定默认可访问性( public
forstruct
和private
for )。class
C语言也允许使用访问修饰符吗?访问说明符真的存在于 C 中吗?
不,C 没有访问说明符。
C++ 中astruct
和 a的唯一区别是 a的成员是默认的,而 a的成员是默认的。您可以在它们中使用访问说明符,就像您可以在它们中使用其他任何东西一样。class
struct
public
class
private
C 中没有访问说明符。