【问题标题】:How to make a scoped variable global in C++?如何在 C++ 中使作用域变量成为全局变量?
【发布时间】:2021-10-11 22:27:06
【问题描述】:

我正在处理一个大型项目,需要将一个作用域变量设为全局变量,以便整个班级都可以访问它。

可能使用它的一个简单场景是使整数x 全局化。

class a
{
public:
    a()
    {
        int x;
    }

    void print()
    {
        std::cout << x << std::endl;
    }
}

更复杂的场景可能包括制作FunctionTypeClass&lt;FunctionType&gt; FunctionTypeDataStore

class thread
{
public:
    template<typename FunctionType>
    thread(FunctionType* function)
    {
        FunctionTypeClass<FunctionType> FunctionTypeDataStore;
    }

    FunctionTypeClass get_function_type()
    {
        return FunctionTypeDataStore;
    }


    ~thread()
    {
    }

    template<typename StoreFunctionTypeTemp>
    class FunctionTypeClass
    {
        StoreFunctionTypeTemp Variable;
    }
}

【问题讨论】:

  • 我认为你应该先弄清楚成员变量是什么,然后再开始将变量设为全局
  • "所以整个班级都可以访问它。"那是一个成员变量,你不需要一个全局变量
  • 你不能让它成为类本身的数据成员吗? class a{ intx; }?

标签: c++ variables global-variables scoped


【解决方案1】:

从中创建一个成员变量,并将您的类模板化,而不是构造函数:

template<typename FunctionType>
class thread
{
private:
    template<typename StoreFunctionTypeTemp>
    class FunctionTypeClass
    {
        StoreFunctionTypeTemp Variable;
    };

    FunctionTypeClass<FunctionType> FunctionTypeDataStore;
public:

    thread(FunctionType* function) { }

    FunctionTypeClass<FunctionType> get_function_type()
    {
        return FunctionTypeDataStore;
    }
};

【讨论】:

  • 虽然这确实有效,但我希望得到一个解决方案,其中涉及使作用域变量成为全局变量。例如,它们是 python 中的 global 关键字,它可以使作用域变量成为全局变量。
  • @anom1 请理解 Python 不是 c++,您应该使用该语言提供的标准 不要试图模仿其他语言的不良行为
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2023-01-05
  • 2013-03-13
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多