假设翻译单元中有一个全局变量。它是常量,但不是编译时常量(它是使用具有非constexpr
构造函数的对象初始化的)。它被声明为static
,因为它应该是翻译单元的私有内容。显然,全局是在.cpp
文件中定义的。但是,现在我已经为需要全局变量的文件添加了一个方法模板。由于它是一种将被其他翻译单元使用的方法,因此必须将其放入标题中。但是,一旦它在标题中,它就不能再访问全局变量。解决这个问题的最佳做法是什么?
答案 0 :(得分:1)
实现目标有一点棘手的方法:
在header中定义的类中使用私有静态变量,并使您的函数/类模板成为此类的朋友。
<强> YourFile.h 强>
class PrivateYourFileEntities {
private:
static const int SomeVariable;
// ... other variables and functions
template <class T>
friend class A;
template <class T>
friend void func();
// the rest of friends follows
};
template <class T>
void A<T>::func() {
int a = PrivateYourFileEntities::SomeVariable;
}
template <class T>
void func() {
int a = PrivateYourFileEntities::SomeVariable;
}
<强> YourFile.cpp 强>
const int PrivateYourFileEntities::SomeVariable = 7;
答案 1 :(得分:-1)
将方法声明放入.h文件和方法体中,如:.cpp文件,如:
.h文件:
#include <iostream>
void myfunc1();
void myfunc2();
.cpp文件:
#include "myheader.h"
static int myglobalvar=90;
void myfunc1()
{
cout << myglobalvar << endl;
}
void myfunc2()
{
cout << "Oh yeah" << endl;
}