简体   繁体   English

C ++命名空间声明和定义

[英]C++ Namespace Declaration and Definition

Folks, 民间,

I crated a name space in a single file, but how exactly do I separate the definition and declaration? 我在单个文件中创建了一个名称空间,但是如何准确地将定义和声明分开呢? Can I create a .h for declaration and a .cpp for definition just like in a class set of file? 是否可以像在文件类集中那样为声明创建.h和为定义创建.cpp? If yes, then, do I need to include the namespace header file in my new program, or is the using namspace mynamespace enough? 如果是,那么是否需要在新程序中包括名称空间头文件,或者使用namspace mynamespace是否足够?

Any decent C++ book should cover namespaces and code separation. 任何体面的C ++书籍都应涵盖名称空间和代码分离。

Try something like this: 尝试这样的事情:

myfile.h myfile.h

#ifndef myfile_H
#define myfile_H

namespace myns
{
    class myclass
    {
    public:
        void doSomething();
    };
}

#endif

myfile.cpp: myfile.cpp:

#include "myfile.h"

void myns::myclass::doSomething()
{
    //...
}

And then you can use it like this: 然后您可以像这样使用它:

#include "myfile.h"

myns::myclass c;
c.doSomething();

Or: 要么:

#include "myfile.h"

using namespace myns;

myclass c;
c.doSomething();

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM