Вопрос

As far as I can tell, you can make your interface known to others by providing your .h file. Your .cpp is the implementation. Then they can see the function names, the parameter types, the return type, maybe a description of how to use a function, and maybe what it does in the .h file.

Then I read in posts here about using namespaces to separate the interface from the implementation. What does that mean? Doesn't a namespace only let you know that a name exists in that namespace? So please provide an example, I can't find any.

Это было полезно?

Решение

You don't use namespaces to separate interface from implementation in C++. Namespaces are essentially packages in C++; you use them to group together related classes.

Rather, you use classes to hide the implementation details from the user. Classes in C++ are the same as classes in any other OOP language in that regard; they provide a public interface, while encapsulating the implementation details.

In the Stack Overflow answer that you linked, the author linked this article. In a nutshell, this article states that any helper functions and operator functions that are part of the functionality of a class should go into the same namespace as that of the class, because they form part of the public API of that namespace.

That makes sense to me. Having those functions in the same namespace organizes the classes (and the functions that support them) within the same logical unit, a logical unit that exposes a public API, but encapsulates the implementation details using ordinary object orientation principles.

Further Reading
Separating Interface and Implementation in C++
The Separation of Interface and Implementation in C++
Namespaces and the Interface Principle

Другие советы

One way to separate "interface" and "implementation" with namespaces is what Boost does: for a library X, put the public API in namespace X and implementation details in namespace X::details or similar.

Лицензировано под: CC-BY-SA с атрибуция
scroll top