我正在努力完成我在C++中的第一步.已经问过这个问题,但没有得到关于命名空间的完整答案.
我做了以下.
Source.cpp
#include <iostream>
using namespace std;
int PrintHello();
extern int tempCount;
void main()
{
int i;
PrintHello();
cout << tempCount << endl;
cout << "Hello from main" << endl;
}
Run Code Online (Sandbox Code Playgroud)
PrintFunc.cpp
#include <iostream>
using namespace std;
int tempCount = 111;
int PrintHello()
{
cout << "Hello from Source1" << endl;
return 0;
}
Run Code Online (Sandbox Code Playgroud)
这是完美的编译.现在我正在学习命名空间,所以我只是尝试将第二个文件的内容放在命名空间中,如下所示.
PrintFunc.cpp(已修改)
#include <iostream>
using namespace std;
namespace MyNameSpace
{
int tempCount = 111;
int PrintHello()
{
cout << "Hello from Source1" << endl;
return 0;
}
}
Run Code Online (Sandbox Code Playgroud)
现在我修改了Source.cpp,以反映前面片段中的命名空间介绍.
#include <iostream>
using namespace std;
int MyNameSpace::PrintHello();
extern int MyNameSpace::tempCount;
void main()
{
int i;
PrintHello();
cout << tempCount << endl;
cout << "Hello from main" << endl;
}
Run Code Online (Sandbox Code Playgroud)
这根本就不能编译.有人可以请你纠正我.我的目标是在c ++中理解命名空间概念.我也用C#做了很好的exp.
编译MYSpace
时编译器不了解命名空间的问题Source.cpp
.
#include <iostream>
using namespace std;
namespace MyNameSpace
{
int PrintHello();
extern int tempCount;
}
int main()
{
int i;
MyNameSpace::PrintHello();
cout << MyNameSpace::tempCount << endl;
cout << "Hello from main" << endl;
}
Run Code Online (Sandbox Code Playgroud)
但这个样本是useless
.它的工作原理只是因为你只有一个消费者.cpp
.
您应该使用.h
文件,然后包括它(PrintFunc.h
中)Source.cpp
和任何其他.cpp
当你想使用funtions.
我会写一个例子:
Print.h
#pragma once
namespace MyNameSpace
{
int PrintHello();
extern int tempCount;
}
Run Code Online (Sandbox Code Playgroud)
请注意,我们dont't使用额外的includes
和using namespace
在这里.我们includes
只会使用一些类functions
interfaces
.
using namespace
可以"破坏"消费者.cpp
或者.h
.
Print.cpp
#include <iostream>
#include "Print.h"
using namespace std;
int MyNameSpace::tempCount = 111;
int MyNameSpace::PrintHello()
{
cout << "Hello from Source1" << endl;
return 0;
}
Run Code Online (Sandbox Code Playgroud)
在这里我们可以设置include
它不会触及任何其他文件.
和消费者.cpp
:
#include <iostream>
#include "Print.h"
using namespace std;
int main()
{
int i;
MyNameSpace::PrintHello();
cout << MyNameSpace::tempCount << endl;
cout << "Hello from main" << endl;
}
Run Code Online (Sandbox Code Playgroud)
VS具体:#pragma once
对于VS,你必须#include "stdafx.h"
在任何一线.cpp
归档时间: |
|
查看次数: |
86 次 |
最近记录: |