[Lab Exercise] Namespaces
Namespaces in C++
Namespaces in C++ are a mechanism for organizing and encapsulating code to prevent naming conflicts and to provide a way to group related functions, classes, or variables together. They are used to create a separate scope for identifiers, ensuring that names don't clash with each other when multiple libraries or parts of a program are combined.
Declaration
namespace MyNamespace {
// Code goes here
}
Scope Resolution
MyNamespace::myFunction();
int x = MyNamespace::myVariable;
Problem Defintion
Write a C++ program that demonstrates the use of namespaces to organize and encapsulate code.
Create a namespace called Math and define the following functions within it:
- int
add(int a, int b)
to perform addition. - int
subtract(int a, int b)
to perform subtraction. - int
multiply(int a, int b)
to perform multiplication. - double
divide(int a, int b)
to perform division and return the result as a double.
Create another namespace called Utils and define the following functions within it:
- void
printMessage(string message)
to print a message to the console. - int
getRandomNumber(int min, int max)
to generate a random integer between the given min and max (inclusive).
In the main part of your program, demonstrate the use of these namespaces by performing the following tasks:
- Use functions from the
Math
namespace to perform arithmetic operations and display the results. - Use functions from the
Utils
namespace to print a message and generate a random number.
Ensure that you correctly declare and use namespaces to encapsulate the functions and avoid naming conflicts.
Comments