为什么这是非法的初始化语法?

时间:2021-02-01 05:27:32
template<typename T>    
void func(T* arr, size_t length)
{
    size_t size_half = length / 2;
    T* left = arr, right = arr + size_half; // Cannot initialize a variable of type 'int' with an rvalue of type 'int *'
}

It seems to me like the compiler thinks right is of type int instead of int*, why?

在我看来,编译器认为正确的类型是int而不是int *,为什么?

3 个解决方案

#1


4  

Because the * is attached to the right, and not the left.

因为*附在右边,而不是左边。

Look at it more like:

看它更像是:

T  *left,  right

That's just how the language syntax is defined. You can fix it by:

这就是语言语法的定义方式。您可以通过以下方式修复:

T *left=...,*right=....;

#2


2  

In types, the * apply to the following , so you should code:

在类型中,*适用于以下内容,因此您应该编码:

template<typename T> void func(T* arr, size_t length) {
  size_t size_half = length / 2;
  T *left = arr, 
    *right = arr + size_half; 
  //etc...
}

Actually, I think that you should declare one pointer per line:

实际上,我认为你应该每行声明一个指针:

  T *left= arr;
  T *right= arr + size_half;

or even (C++11 style):

甚至(C ++ 11风格):

  T *left {arr};
  T *right {arr + size_half};

or

  auto left {arr};
  auto right {arr + size_half};

declaring each pointer on its line is IMHO much more readable.

在其行上声明每个指针是恕我直言更可读。

BTW, you might consider using std::array<T> or std::vector<T>

顺便说一下,您可以考虑使用std :: array 或std :: vector

#3


0  

It will be like this

它会是这样的

T *left = arr, *right = arr + size_half;

#1


4  

Because the * is attached to the right, and not the left.

因为*附在右边,而不是左边。

Look at it more like:

看它更像是:

T  *left,  right

That's just how the language syntax is defined. You can fix it by:

这就是语言语法的定义方式。您可以通过以下方式修复:

T *left=...,*right=....;

#2


2  

In types, the * apply to the following , so you should code:

在类型中,*适用于以下内容,因此您应该编码:

template<typename T> void func(T* arr, size_t length) {
  size_t size_half = length / 2;
  T *left = arr, 
    *right = arr + size_half; 
  //etc...
}

Actually, I think that you should declare one pointer per line:

实际上,我认为你应该每行声明一个指针:

  T *left= arr;
  T *right= arr + size_half;

or even (C++11 style):

甚至(C ++ 11风格):

  T *left {arr};
  T *right {arr + size_half};

or

  auto left {arr};
  auto right {arr + size_half};

declaring each pointer on its line is IMHO much more readable.

在其行上声明每个指针是恕我直言更可读。

BTW, you might consider using std::array<T> or std::vector<T>

顺便说一下,您可以考虑使用std :: array 或std :: vector

#3


0  

It will be like this

它会是这样的

T *left = arr, *right = arr + size_half;