当我们不想用对象调用函数时,如何编写和调用不带对象的函数
how to write and call a function without object when we dont want to call with an object
我正在使用不同的类以及与这些不同类相关的对象。现在,我想写一个单独的函数用来连接两个向量到另一个向量。我应该在哪里写这些不同的函数。我可以使用一个新的头文件吗?实际上,我做了一个新的头文件(ConnectedSegment.h),并把我的函数。但是,我得到了这个错误。
43 D:myexConnectedSegment.h non-member function `std::vector<int>& NeighboursToGivenValue(std::map<int, std::vector<int> >&, int, int)' cannot have `const' method qualifier
D:myexDetectsMakefile.win [Build Error] [Detects.o] Error 1
下面是我的函数代码:
vector<int> & NeighboursToGivenValue(map<int, vector<int> > &adjacency,
int s1, int s2) const
{
vector<int>::const_iterator any;
vector<int>::iterator is_any;
vector<int> *neighbours2both = new vector<int>;
int i;
neighbours2both->reserve(adjacency[s1].size() + adjacency[s2].size());
neighbours2both->insert(neighbours2both->end(), adjacency[s1].begin(),adjacency[s1].end ());
vector<int>& neighbours2s2=adjacency[s2];
for (any=neighbours2s2.begin(); any!=neighbours2s2.end(); any++){
is_any = find (neighbours2both->begin(), neighbours2both->end(), *any);
if(is_any == neighbours2both->end()){
if(s1 != *any) neighbours2both->push_back(*any);
}
}
for (i=0; i<neighbours2both->size(); i++){
neighbours2both->erase(neighbours2both->begin() + i);
}
return(*neighbours2both);
}
在这里,我通过使用另一个称为MyPoint
的类获得了adjacency()
的值。所以我使用myxyz.adjacency()
来适应这个邻接的值。现在我不想调用同一个类MyPoint
来调用函数NeighboursToGivenValue
。所以,你能告诉我应该在哪里写这个函数吗?或者,如果我在MyPoint
类中编写这个函数,我怎么能在没有该类对象的情况下调用这个函数呢?
这些自由的函数可以在头文件中(需要在inline
中声明,正如Pedro在他的注释中强调的那样)—或者它们可以在头文件中声明并在实现文件中定义—例如,
#header
vector<int>& join_int_vector(vector<int> const& lhs, vector<int> const& rhs);
# cpp
vector<int>& join_int_vector(vector<int> const& lhs, vector<int> const& rhs)
{
// do stuff
}
你面临的问题是你只能有const成员函数——也就是说自由函数(和静态函数)不能是const
——它没有任何意义。
顺便说一句。不要动态构造一个vector并返回对它的引用,例如:
vector<int> *neighbours2both = new vector<int>;
:
return (*neighbours2both);
被调用方不知道该对象需要手工清理——在这种情况下,按值返回。
vector<int> join_int_vector(vector<int> const& lhs, vector<int> const& rhs)
{
vector<int> neighbours2both;
:
return neighbours2both;
}
编辑:对于头文件中定义的函数,像这样:
inline vector<int> join_int_vector(vector<int> const& lhs, vector<int> const& rhs)
{
vector<int> neighbours2both;
:
return neighbours2both;
}
注意关键字inline
的使用-这可以防止多个定义错误,如果这个头包含在多个翻译单元。
相关文章:
- 函数调用中参数的顺序重要吗
- 基于另一个成员参数将函数调用从类传递给它的一个成员
- 变量没有改变?通过向量的函数调用
- 在两个类中共享相同的函数调用,并在不需要时避免空实例化
- 是否有C++编译器选项允许激进地删除所有函数调用,并将参数传递给具有空体的函数
- 我知道函数调用中存在歧义.有没有办法调用foo()函数
- 模板函数调用
- 获取从C++中同一类中的构造函数调用的方法返回的值
- 析构函数调用
- 成员函数调用和C++对象模型
- 使用共享指针的函数调用,其对象应为 const
- C++:编译时检查匹配的函数调用对?
- 函数调用C++中的参数太少
- 来自 DLL 的函数调用 [表观调用的括号前面的表达式必须具有(指向-)函数类型]
- 返回指向对象的指针的函数调用是否为 prvalue?
- C++ 如何重载 [] 运算符并进行函数调用
- 代码的效率. 转到和函数调用
- 是同一作用域的函数部分中的函数调用
- 如何封装一个函数,以便它只能由同一类中的一个其他函数调用?
- 类型擦除的std::function与虚拟函数调用的开销