我有两个文件Sample.cpp和Main_file.cpp.Sample.cpp只有一个名称空间n1,其中包含int变量的定义x.我想x在main_file.cpp中打印这个变量.我该怎么做呢?
//Sample.cpp_BEGINS
namespace n1
{
int x=10;
}
//Sample.cpp_ENDS
//Main_FILE_BEGINS
void main()
{
print x;
}
//MAIN_FILE_ENDS
Run Code Online (Sandbox Code Playgroud)
感谢您提供任何帮助.
要从n1::xmain.cpp访问,您可能想要创建并包含sample.h:
// sample.h
#ifndef SAMPLE_H
#define SAMPLE_H
namespace n1
{
extern int x;
}
#endif
Run Code Online (Sandbox Code Playgroud)
// sample.cpp
#include "sample.h"
namespace n1
{
int x = 42;
}
Run Code Online (Sandbox Code Playgroud)
#include <iostream>
#include "sample.h"
int main()
{
std::cout << "n1::x is " << n1::x;
}
Run Code Online (Sandbox Code Playgroud)
如果您不想创建头文件,也可以在main.cpp中执行此操作:
#include <iostream>
namespace n1
{
extern int x;
}
int main()
{
std::cout << "n1::x is " << n1::x;
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
135 次 |
| 最近记录: |