How can I use namespaces in C ++ files?

I have 2 .cpp files

a1.cpp

#include <iostream>
#include <conio.h>

using namespace std;

using namespace te;

int main(int argc, char ** argv)
{
    A a1(5);
    cout<<a1.display();
    return 0;
}

a2.cpp

#include <iostream>

namespace te
{
    class A{
        int i;
    public:
        A(int a)
        {i = a;}
        int display()
        {
            return i;
        }
    };
}

How to use te in a1.cpp? Can I do this using header files?

+3
source share
4 answers

Yes, you need to a2.h. Add namespace te{ class A { public: A(int a); int display();};}to the header file and include the header file froma1.cpp

+1
source
#include <iostream>
#include <conio.h>

#include "a2.cpp"

int main(int argc, char ** argv)
{
    te::A a1(5);
    std::cout << a1.display() << std::endl;
    return 0;
}

This means that it a2.cppis in the same folder as a1.cpp. However, it is better to make this a header file.

You should keep in mind that this should usually be avoided using namespace XX;, and you should just have direct material. egstd::cout

, conio.h C edit:, cout, C++. (Credits to DeadMG , . ).

+2

A te a1 .

+1

, , : te a1.cpp(using namespace te;). te::A, #include . , a2.cpp, a1.cpp( .cpp ).

+1

Source: https://habr.com/ru/post/1781645/


All Articles