2011-08-27 89 views
0
struct G{ 

    G&operator()(const int**a) 
    { 
     v<<a; 
     std::copy(v.begin(),v.end(),std::ostream_iterator<int>(std::cout, " ")); 
     return *this; 
    } 
    friend std::vector<int>&operator<<(std::vector<int>&v,const int** n); 
    std::vector<int>v; 
}; 

std::vector<int>&operator<<(std::vector<int>&v,const int** n) 
{ 
    v.insert(v.begin(),*n,*n+sizeof(*n)/sizeof(*n[0])); 
    return v; 
} 

/// use it 
G g; 
int v[8]={1,2,3,4,5,6,5,4}; 
g(&v); 

我有两个问题,我想在克为g({1,2,3,4传递 1.错误cannot convert parameter 1 from 'int (*)[8]' to 'const int **'
2.上述代码返回的数组, 5,6,5,4})而不是g(&v)。但我不知道该怎么做,总是想知道g是否会接受它。
谢谢。传递参数作为整数

+0

尝试使用以下内容:'template myFunction(int&myArray [N])'这种方式可以防止它在函数调用中指向int的指针衰减。 :) –

回答

0
  1. &v给你的数组地址,当你想要一个指针的地址。尝试做const int* x = v,然后g(&x)
  2. 在C++ 0x中,你可以这样做:

    G& operator()(std::initializer_list<const int>); 
    g({1,2,3,4,5,6,5,4}); 
    
1

如果你知道你将永远使用尺寸为8的一个常量数组,

struct G{ 

    G&operator()(int a[8]) 
    { 
     v.reserve(8); 
     v.insert(v.begin(), a, a + 8); 
     std::copy(v.begin(),v.end(),std::ostream_iterator<int>(std::cout, " ")); 
     return *this; 
    } 

    std::vector<int>v; 
}; 

/// use it 
G g; 
int v[8]={1,2,3,4,5,6,5,4}; 
g(v); 

如果没有,你需要将阵列的大小与阵列一起传递:

struct G{ 

    G&operator()(int* a, int len) 
    { 
     v.reserve(len); 
     v.insert(v.begin(), a, a + len); 
     std::copy(v.begin(),v.end(),std::ostream_iterator<int>(std::cout, " ")); 
     return *this; 
    } 

    std::vector<int>v; 
}; 

/// use it 
G g; 
int v[8]={1,2,3,4,5,6,5,4}; 
g(v, sizeof(v)/sizeof(int)); 

或者,如果你总是要使用编译时间阵列(从他们所宣称的范围),而不是动态数组,

struct G{ 

    template<unsigned int Len> 
    G& operator()(int (&a)[Len]) 
    { 
     v.reserve(Len); 
     v.insert(v.begin(), a, a + Len); 
     std::copy(v.begin(),v.end(),std::ostream_iterator<int>(std::cout, " ")); 
     return *this; 
    } 

    std::vector<int>v; 
}; 

/// use it 
G g; 
int v[]={1,2,3,4,5,6,5,4}; 
g(v); 

但要注意的是最后一个版本会产生不同版本的operator()每一个不同你通过它的数组大小。

+1

如果与模板版本的代码重复成为问题,您可以通过将该数组转发并将其大小转换为动态版本来部分缓解该问题,在该版本中将完成实际工作。 –