当我们不想用对象调用函数时,如何编写和调用不带对象的函数

how to write and call a function without object when we dont want to call with an object

本文关键字:函数 调用 对象 何编写 我们 不想      更新时间:2023-10-16

我正在使用不同的类以及与这些不同类相关的对象。现在,我想写一个单独的函数用来连接两个向量到另一个向量。我应该在哪里写这些不同的函数。我可以使用一个新的头文件吗?实际上,我做了一个新的头文件(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的使用-这可以防止多个定义错误,如果这个头包含在多个翻译单元。