C++的namespace

发布时间 2023-04-16 14:25:19作者: Z_Chan

这个也是和Java不同的地方,作用是为了防止类的名字冲突

#include <iostream>
namespace myspace{
    class A{
        public:
            std::string head;
        private:
            std::string body;
    };
}
namespace myspace2{
    class A{
        public:
            std::string head;
        private:
            std::string body;
    };
}
int main()
{
using namespace myspace;
using namespace myspace2;
   A a;
   a.head="888";
   //a.body="999";
   return 0;
}

你这样一搞namespace就没有任何意义

#include <iostream>
namespace myspace{
    class A{
        public:
            std::string head;
        private:
            std::string body;
    };
}
namespace myspace2{
    class A{
        public:
            std::string head;
        private:
            std::string body;
    };
}
int main()
{
   using myspace::A;
   A a;
   a.head="888";
   //a.body="999";
   return 0;
}

一般这样用