简体   繁体   English

Class 成员 function 在公共、受保护和私有之外声明

[英]Class member function declared outside of public, protected and private

I came across some code that looked like this:我遇到了一些看起来像这样的代码:

class SomeClass {
   void SomeFunction();

public:
   ~~ public members
}

There were no private or protected members of the class. class 没有私有或受保护成员。

My question is;我的问题是; is not labelling what part of the class the 'SomeFunction' belongs to bad programming?没有标记 class 的哪个部分“SomeFunction”属于不良编程? Or does defining the function in this way implicitly assign it to some part of the class, ie private or protected, since it is not part of the public members?或者以这种方式定义 function 是否隐含地将其分配给 class 的某些部分,即私有或受保护,因为它不是公共成员的一部分?

In C++, the difference between class and struct is that for a struct everything is implicitly public and for a class everything is implicitly private .在 C++ 中, classstruct之间的区别在于,对于struct ,所有内容都是隐式public的,而对于class ,所有内容都是隐式private的。

As soon as you use explicitly public: , private: or protected: the behavior is the same in both cases for the following members.只要您明确使用public:private:protected:在两种情况下,以下成员的行为都是相同的。

This is true about inheritance too. inheritance 也是如此。
struct A: B is a public inheritance. struct A: B是公共 inheritance。
class A: B is a private inheritance. class A: B是私有 inheritance。

In your example, SomeFunction() is in the implicit part of the class , so it is considered private .在您的示例中, SomeFunction()位于class隐式部分,因此它被视为private

A very well respected C++ expert considers this kind of declaration (implicitly private ) as a good practice.一位非常受人尊敬的 C++ 专家认为这种声明(隐式private )是一种很好的做法。
( https://howardhinnant.github.io/classdecl.html ) https://howardhinnant.github.io/classdecl.html

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 为什么此公共成员函数不能在类内部声明的私有struct成员上调用decltype? - Why can't this public member function call decltype on a private struct member declared inside the class? 在使用受保护和 inheritance 时无法访问在 class 中声明的私有成员 - cannot access private member declared in class while using protected and inheritance 为什么我们不允许在没有公共成员函数的情况下访问类外的私有静态成员? - Why aren't we allowed to access a private static member outside class without public member function? 在类外调用的私有函数成员 - Private function member called outside of class 每个成员公共/受保护/私人? - Per-member public/protected/private? 在其他类别中声明的私人成员 - Private member declared in other class 允许访问命名空间之外的 class 的受保护成员 function - Allowing access to protected member function for class outside of namespace 在函数中使用Ifstream(无法访问在类中声明的私有成员) - Using Ifstream within a function (cannot access private member declared in class) 使用公共成员函数访问私有成员变量时出错:变量“未在此范围内声明” - Error when using public member function to access private member variable: Variable “was not declared in this scope” 错误:成员 function 不得在其 class 之外声明。 - Error: member function may not be declared outside of its class.
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM