【问题标题】:Changing variables in namespaces更改命名空间中的变量
【发布时间】:2021-07-28 02:18:17
【问题描述】:

我想在命名空间中声明一个数组,然后从另一个文件中定义它,并在定义后从第三个文件中访问它。谁能帮我?顺便说一句,我愿意使用int[] 或std::array。

//name.h
#pragma once
namespace Info {
    int arr[2];
    array<int, 2> arra;
}


//file1.cpp
#include "name.h"
using namespace Info;

arr = {10, 9}
arra = {10, 9}

//main.cpp
#include "name.h"
#include <iostream>
int main() {
    cout<<arr[0]<<endl;
}

【问题讨论】:

  • 您可以使用原始数组或std::array,尽管后者在 C++ 中通常被认为更可取。在头文件中将它们声明为extern,并在项目的单个源文件中将它们(例如int Info::arr[] = {10,9} 或std::array&lt;int, 2&gt; Info::arra {10,9}; 或namespace Info {int arr[2] = {10,9};})定义一次。然后可以由任何包含标头的源文件访问它们。另外,不要在标题中使用using namespace std - 即使是基本搜索也会解释为什么这是不好的做法。

标签: c++ namespaces


【解决方案1】:

代码可能如下所示

// header file
namespace Info
{
     extern int arr[2];
}

// file1.cpp
namespace Info
{
     int arr[2] = { 2, 3 };
}

添加extern 关键字使其声明不是定义(不允许有多个定义)。

如果您可以在头文件中使用初始化程序,那么代码可以简化为(C++17 起):

// header file
namespace Info
{
    inline int arr[2] = { 2, 3 };
}

并且不需要其他定义。 std::array 版本的工作方式相同。

【讨论】:

    猜你喜欢
    • 2016-04-08
    • 2012-08-13
    • 2017-10-05
    • 1970-01-01
    • 2014-07-05
    • 1970-01-01
    • 2010-10-14
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多