我围绕 GSL 的某些部分编写了一个小的 C++ 包装器,并遇到了以下难题(对我而言)。代码(简化为基本内容)如下:
#include <stdlib.h>
struct gsl_vector_view {};
class Vector : protected gsl_vector_view {
public:
Vector ( const Vector& original );
Vector ( const gsl_vector_view view );
};
class AutoVector : public Vector {
public:
explicit AutoVector ( const size_t dims );
};
void useVector ( const Vector b ) {}
void test () {
const AutoVector ov( 2 );
useVector( ov );
}
不会使用 gcc 4.4.5 g++ -c v.cpp 编译但会产生
In function ‘void test()’:
19: error: call of overloaded ‘Vector(const AutoVector&)’ is ambiguous
7: note: candidates are: Vector::Vector(gsl_vector_view)
6: note: Vector::Vector(const Vector&)
19: error: initializing argument 1 of ‘void useVector(Vector)’
我很惊讶,受保护的基类 gsl_vector_view 被调用 useVector( Vector ) 考虑在内。我会认为 useVector 属于“C++ 编程语言”的说法中的“公众”,第 3 e.,p。405,因此无法访问该受保护的信息,因此不会被它混淆。我知道我可以通过将构造函数声明为来消除歧义
explicit Vector ( const gsl_vector_view view );
我不知道(老实说,也不明白),当我将构造函数声明为时,重载调用的歧义消失了
Vector ( const gsl_vector_view& view );
即通过引用传递参数(无论如何我都会考虑正确的做事方式)。