- Game Development Patterns and Best Practices
- John P. Doran Matt Casanova
- 357字
- 2021-07-02 23:43:45
An overview on class access specifiers
When using an object-oriented programming language, one of the most important features included is the ability to hide data, preventing classes from accessing properties and functions of another class type by default. By using access specifiers such as public, private, and protected, we can dictate specifically how the data and/or functions can be accessed from other classes:
class ModifierExamples
{
public int publicInteger;
private void PrivateMethod() {}
protected float protectedNumber;
};
A class can have unlimited variables or functions that are public, private, or protected and can even control access to entire sections of the class:
class MoreModifierExamples
{
public:
// until we reach another tag, all variables and functions
// will be public
int publicIntegar;
int anotherExample;
private:
// Now, they'll be private
void PrivateFunction() {}
double safeValue;
protected:
// And now... protected
float protectedNumber;
int AlsoProtected() { return 0; }
};
When you place a labelled section with an access modifier's name and a : next to it, until there is another section label, all of the parts of the class that are listed will use that specific one.
When we use the public access modifier, we are saying that this variable or function can be used or accessed from anywhere within our program, even outside of the class we've created. Declaring a variable outside of a function or class, or marking a variable as public and static, is often referred to as being a global variable. We will be talking about global variables in the next section, but for right now, let's go over the other access specifiers as well.
When private is used, we are restricting the usage of our variable or function to being allowed only inside of the class, or from friend functions. By default, all of the variables and functions in a class are private.
For more information on friend functions, check out http://en.cppreference.com/w/cpp/language/friend.
The third type, protected, is the same as a private type except that it can still be accessed by child (or derived) classes. This can be quite useful when using inheritance so you can still access those variables and/or functions.
- 前端跨界開發(fā)指南:JavaScript工具庫原理解析與實(shí)戰(zhàn)
- 程序員面試算法寶典
- 數(shù)據(jù)結(jié)構(gòu)簡(jiǎn)明教程(第2版)微課版
- Blender 3D Incredible Machines
- JSP開發(fā)案例教程
- QGIS:Becoming a GIS Power User
- jQuery開發(fā)基礎(chǔ)教程
- Access 2010中文版項(xiàng)目教程
- 大話Java:程序設(shè)計(jì)從入門到精通
- Creating Data Stories with Tableau Public
- Troubleshooting Citrix XenApp?
- Python程序設(shè)計(jì)開發(fā)寶典
- 創(chuàng)意UI Photoshop玩轉(zhuǎn)移動(dòng)UI設(shè)計(jì)
- Java程序設(shè)計(jì)基礎(chǔ)(第6版)
- WordPress Search Engine Optimization(Second Edition)