如何使用与函数同名的变量?

How do I use a variable that has the same name as a function?

本文关键字:变量 何使用 函数      更新时间:2023-10-16

我有给定的模板类,具有以下属性/类

template<class T1, class T2, int max>
class Collection{
T1 * _elementi1[max];
T2 * _elementi2[max];
int currently;
public:
Collection() {
for (size_t i = 0; i < max; i++) {
_elementi1[i] = nullptr;
_elementi2[i] = nullptr;
}
currently = 0;
}
~Collection() {
for (size_t i = 0; i < max; i++) {
delete _element1[i]; _element1[i] = nullptr;
delete _element2[i]; _element2[i] = nullptr;
}
}
T1 ** GetT1() { return _element1; }
T2 ** GetT2() { return _element2; }
int GetCurrent() { return currently; }
void Add(T1 t1, T2 t2) {
if (currently == max)
{
throw exception("MAX SIZE REACHED");
}
_element1[currently] = new T1(t1);
_element2[currently] = new T2(t2);
++currently;
}
friend ostream& operator<< (ostream &COUT, Collection&obj) {
for (size_t i = 0; i < obj.currently; i++)
COUT << *obj._element1[i] << " " << *obj._element2[i] << endl;
return COUT;
}

};

Max用于限制集合的容量(我知道很愚蠢..(问题是我使用的#include <algorithm>也有一个叫做max的函数。每次我想使用变量智能感知和编译器时,都使用函数而不是变量。如何告诉编译器使用变量max而不是函数?

在人们提交代码改进和其他建议之前也是如此。这是一个考试示例,其中不允许重命名/修改变量,您只能添加您认为合适的内容。

未经修改的"考试示例"是否编译?

是的,假设我不包括算法,它确实如此

我会说这是您在某处添加"使用命名空间 std;"的证据,也许是为了从算法<中获得一些功能>

如何告诉编译器使用变量 max 而不是 功能?

一种方法是取消编译器请求,将所有或任何命名空间 std 函数拉入本地命名空间......我的意思是删除"使用命名空间 std;">

现在,也许您需要<算法>的功能......如何在不同时拉入"std::max"的情况下获得它

示例:从<算法>,我经常使用 shuffle((

#include <algorithm>
// ... then I usually do 
std::shuffle (m_iVec.begin(), m_iVec.end(), gen);
// I have no problem using the std:: prefix.

此时,函数 std::max(( 也被编译器知道,但不会与您的变量名称冲突。 访问该函数的唯一方法是通过"std::max(("符号。


还有另一种形式的"使用",如下所示:

#include <algorithm>
// now 'bring in' the feature you want.
using  std::shuffle; // pull in shuffle, BUT NOT std::max
// ... so I now can do 
shuffle (m_iVec.begin(), m_iVec.end(), gen);
// and have no worries about max being interpreted as a function
max = 0;

永远之后,我必须搜索我在这里调用的"shuffle(("方法的提示/提醒。