开发者

C++ access specifiers, too few?

As far as i know, there're only 3 access-specifiers in C++: private, public, protected

With these 3 access-specifiers, how can i make a method usable 开发者_C百科to the classes in the project but unusable to the "foreigners" ??(like internal and public in C#)


C++ does not know what a project is.

C++ knows about classes, where it offers the three access specifiers you mentioned.

C++ knows about translation units, where it offers two access specifiers: internal and external linkage.

Edit: About internal and external linkage, this is related to whether a symbol will be seen outside of the translation unit (the object file). Any global static or const variable defined in the TU has internal linkage. Others have external linkage.


Put simply, you don't. C++ is not anything like C#.

If you don't want to make a class available outside a given library or executable, then simply don't provide the header file to users of your project.


You can use the passkey friend idiom.

This isn't a term you'll be able to search for, though. The idea isn't new, though not terribly common, and sort of arose on SO. The link above is my attempt at a generic solution (impossible to do cleanly in C++03, beautiful in C++0x).

I'm sure there are other ways to try to do it, but for some reason I have an attachment to the above...:)


But otherwise, no. A far more common and simpler solution is to just throw your stuff in a detail namespace (common throughout Boost, for example), and say "don't go there".


The two closest things that you have to a solution are

  1. Have an internal namespace that you use in your code which you don't really publicize. Users of your library then use whatever namespace that you use that is intended for public consumption. However, it's not enforced. It's just obfuscated in that they won't necessarily know about the namespace or are told not to use it, so they don't.

  2. Use friend. This is enforced by the compiler. If a class is a friend of another class, or if a function is a friend of a class, then it can access its private member functions while others can't. Unfortunately, that means that the friend has access to all private members, so it can give more access to various classes or functions than you'd like (though it would be within your own classes and functions rather than that of the users of your library).

C++ is older than such languages as C#, Java, and D which give you finer grained control over access levels. C++ pioneered a lot of this sort of stuff, and it didn't always get it right. Designers of newer languages have learned from it and improved upon it in many ways, so you're going to find certain concepts in newer languages which C++ just doesn't have (though sometimes C++ has concepts that newer languages didn't adopt). Other example would be packages and sealed/final classes and functions.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜