Preventing Name Collisions with Namespaces, Use namespaces to modularize code. - C++ Statement

C++ examples for Statement:namespace

Introduction

With namespaces, you can group large groups of code in separate files into a single namespace.

You can nest namespaces to partition a large module into submodules.

// Devices.h
#ifndef DEVICES_H__
#define DEVICES_H__

#include <string>
#include <list>

namespace hardware {
   class IOS {
   public:
      IOS() : uptime_(0), status_("unknown") {}
      unsigned long getUptime() const;
      std::string getStatus() const;
      void reset();
   private:
      unsigned long uptime_;
      std::string status_;
   };

   class IOSMgr {
   public:
      void getIOSIds(std::list<std::string>& ids) const;
      IOS getIOS(const std::string& id) const;
      // Other stuff...
   };
}

#endif // DEVICES_H__

// IOSs.cpp
#include "IOSs.h"
#include <string>
#include <list>

namespace hardware {

   using std::string;
   using std::list;

   unsigned long IOS::getUptime() const {
      return(uptime_);
   }

   string IOS::getStatus() const {
      return(status_);
   }

   void IOSMgr::getIOSIds(list<string>& ids) const {
   }

   IOS IOSMgr::getIOS(const string& id) const {
      IOS d;
      return(d);
   }
}

// IOSWidget.h
#ifndef DEVICEWIDGET_H__
#define DEVICEWIDGET_H__

#include "IOSs.h"

namespace ui {

   class Widget { /* ... */ };
   class IOSWidget : public Widget {
   public:
      IOSWidget(const hardware::IOS& dev) : device_(dev) {}
      // Some other stuff
   protected:
      hardware::IOS device_;
   };
}
#endif // DEVICEWIDGET_H__

// main.cpp
#include <iostream>
#include "IOSWidget.h"
#include "IOSs.h"

int main() {

   hardware::IOS d;
   ui::IOSWidget myWidget(d);
   // ...
}

Related Tutorials