r****t 发帖数: 10904 | 1 这个应该是常见问题了,google 了一下确没有找到,这段小程序不能 compile:
template
class A {
public:
A(float numbers[N]):
numbers(numbers) {}
float numbers[N]; // this does not compile, see error msg below.
//float* numbers; // this works fine.
};
float arr[3] = {1.,2.,3.};
int main() {
A<3> a(arr);
}
compile 错误是:
test3.cpp: In constructor 'A::A(float*) [with int N = 3]':
test3.cpp:14: instantiated from here
test3.cpp:5: error: incompatible types in assignment | x****u 发帖数: 44466 | 2 数组不是C++的类型,放在参数里面就等于const pointer,你用union包装一下吧。
below.
【在 r****t 的大作中提到】 : 这个应该是常见问题了,google 了一下确没有找到,这段小程序不能 compile: : template : class A { : public: : A(float numbers[N]): : numbers(numbers) {} : float numbers[N]; // this does not compile, see error msg below. : //float* numbers; // this works fine. : }; : float arr[3] = {1.,2.,3.};
| r****t 发帖数: 10904 | 3 用union包装是啥意思呢?展开说说?
【在 x****u 的大作中提到】 : 数组不是C++的类型,放在参数里面就等于const pointer,你用union包装一下吧。 : : below.
| p***o 发帖数: 1252 | 4 memcpy or std::copy
below.
【在 r****t 的大作中提到】 : 这个应该是常见问题了,google 了一下确没有找到,这段小程序不能 compile: : template : class A { : public: : A(float numbers[N]): : numbers(numbers) {} : float numbers[N]; // this does not compile, see error msg below. : //float* numbers; // this works fine. : }; : float arr[3] = {1.,2.,3.};
| r****t 发帖数: 10904 | 5 我觉得在 ctor 里面 memcpy 应该是个好办法。
【在 p***o 的大作中提到】 : memcpy or std::copy : : below.
| t****t 发帖数: 6806 | 6 first of all, you can not copy array by using numbers(numbers). must use
memcpy or std::copy.
second, if you declare ctor as A::A(float numbers[N]), it is equivalent to A
float[1] without compiling errors, which may not be desirable. depending on
your requirement, you may want to use
A::A(const float (&numbers)[N])
as ctor, which preserves length information and enforces that you can only
send in float[N] at compile time.
below. | r****t 发帖数: 10904 | 7
A
on
对,这个是唯一用一个 argument 还能 enforce N 的办法
【在 t****t 的大作中提到】 : first of all, you can not copy array by using numbers(numbers). must use : memcpy or std::copy. : second, if you declare ctor as A::A(float numbers[N]), it is equivalent to A : float[1] without compiling errors, which may not be desirable. depending on : your requirement, you may want to use : A::A(const float (&numbers)[N]) : as ctor, which preserves length information and enforces that you can only : send in float[N] at compile time. : below.
|
|