C++ 如何在以指针为参数的标头中声明函数?

C++ 如何在以指针为参数的标头中声明函数?,c++,C++,到目前为止,我已经解决了很多Euler问题,并且一直在考虑一种更聪明的方法来重用我为早期问题编写的函数。所以我想制作一个包含所有有用函数的头文件。到目前为止,我已经能够成功地将它包含在我的头文件中,没有任何错误 #include <cmath> bool isPrime(long int n) { if( n<=0 ) return false; if( n==1 ) return false; else if( n < 4 ) return true;

到目前为止,我已经解决了很多Euler问题,并且一直在考虑一种更聪明的方法来重用我为早期问题编写的函数。所以我想制作一个包含所有有用函数的头文件。到目前为止,我已经能够成功地将它包含在我的头文件中,没有任何错误

#include <cmath>
bool isPrime(long int n)
{
  if( n<=0 ) return false; 
  if( n==1 ) return false;
  else if( n < 4 ) return true;
  else if( n%2 == 0 ) return false;
  else if( n<9 ) return true;
  else if( n%3 == 0 ) return false;

  else{ 
    int r = floor(sqrt(n)); 
    int f = 5;
    while( f <= r ){ 
      if(n%f == 0) return false;
      if(n%(f+2) == 0) return false;
      f += 6; 
    }

    return true;
  }
}
#包括
bool isPrime(长整数n)
{

如果(n
std::
缺失:

还有一些改进,常量引用优于指针

template <typename T>
void printVec(const std::vector<T>& a) {
  for (std::size_t i = 0; i != a.size(); ++i) {
    std::cout << a.at(i) << ", ";
  }
  std::cout << std::endl;
}
模板
void printVec(const std::vector&a){
对于(std::size_t i=0;i!=a.size();++i){

std::cout只需在includes之后添加
namespace std;
以确保您正在使用namespace std即可。如果使用C++11,这将解决您的问题:

#include <iostream>
#include <vector>

using namespace std;

template <typename T>
void printVec(vector<T> a){
  for(auto vectorElement: a)
    cout << vectorElement << ", ";
  cout << endl;
}

int main(void){
    vector<int> aVec = {1,2,3,4};
    printVec(aVec);
}
#包括
#包括
使用名称空间std;
模板
无效打印向量(向量a){
用于(自动矢量元素:a)

cout vector位于std名称空间中,例如count和endl。您在头文件中使用过名称空间std吗?您忘记了
std:
之前的
vector
。但是为什么要首先使用指针呢?请改用
const std::vector&a
。如果您想在头文件中定义非模板函数,您必须使它们成为
static
inline
,或者那些函数在包含头文件的所有位置都有定义,这将导致多个定义链接器错误。不,我忘了包含std名称空间,谢谢。
template <typename T>
void printVec(const std::vector<T>& a){
  for (const auto& e : a) {
    std::cout << e << ", ";
  }
  std::cout << std::endl;
}
void printVec(const std::vector<T>& a){
    std::copy(a.begin(), a.end(), std::ostream_iterator<T>(std::cout, ", "));
    std::cout << std::endl;
}
#include <iostream>
#include <vector>

using namespace std;

template <typename T>
void printVec(vector<T> a){
  for(auto vectorElement: a)
    cout << vectorElement << ", ";
  cout << endl;
}

int main(void){
    vector<int> aVec = {1,2,3,4};
    printVec(aVec);
}