此代码段不能使用VS2013或ICC 16进行编译:
class C2;
class C1
{
public:
float x, y;
template<typename T>
C1 (T x, T y) : x(static_cast<float>(x)), y(static_cast<float>(y)) {};
C1 (const C2 &a, int i) : x(0), y(0) {};
};
void main()
{
C1 p(1.5, 2);
}
Run Code Online (Sandbox Code Playgroud)
因为没有C1构造函数的实例匹配参数列表(double, int),但是当我C2用PolyLine它替换它时会编译并1.5以某种方式转换为PolyLine.我在一个有很多依赖项的大型项目中测试它,所以我只能在这里放入标题的一个片段:
class PolyLine
{
protected:
enum {INIT_LENGTH = 16};
public:
typedef float (PolyLine::*Fit)(Point2D&, Point2D&, const int, const int, const float) const;
vector<float> x; ///< Vector with X axis coordinates of polyline nodes.
vector<float> y; ///< Vector with Y axis coordinates of polyline nodes.
PolyLine (int initLength = INIT_LENGTH);
PolyLine (const PolyLine &poly, int firstNode = -1, int lastNode = -1);
PolyLine (const PolyLine &poly, const float MAX_ERROR, vector<int> *nodeMap = 0);
PolyLine (ifstream* input);
PolyLine (string fileName) {loadTxt (fileName);};
PolyLine (const float SAMPLING_RESOLUTION, PolyLine &poly);
PolyLine (const vector<float> &v, float step = 1.0);
PolyLine (const vector<int> &v, float step = 1.0);
PolyLine (const deque<float> &x, const deque<float> &y) : x(x.begin(), x.end()), y(y.begin(), y.end()) {};
Run Code Online (Sandbox Code Playgroud)
什么时候PolyLine可以施展double?
编辑
在阅读完第一个答案后,我将此示例缩减为:
class PolyLine
{
public:
PolyLine(int i = 7) {};
};
Run Code Online (Sandbox Code Playgroud)
标记PolyLine构造函数explicit产生期望的效果.
你正打算打电话C1::C1(double, int).找到两个名称:
template <typename T> C1::C1(T, T);
C1::C1(const C2&, int);
Run Code Online (Sandbox Code Playgroud)
第一个是不可行的 - 你的参数有不同的类型,所以你不能在一个类型上调用模板.
这样就留下了第二个.如果你C2能从a 构造一个,那么第二个是可行的double.在您的初始示例中,它C2是不完整的,因此您无法从任何内容构造它,因此无法编译.但是,因为PolyLine我们有这个构造函数:
PolyLine (int );
Run Code Online (Sandbox Code Playgroud)
作为转换序列的一部分,我们可以进行零次或一次标准转换以及零次或一次用户定义转换.double --> int是允许的标准转换,int --> PolyLine是允许的用户定义转换.
因此,它C1::C1(const PolyLine&, int)是一个可行的构造函数.因为它是唯一可行的构造函数,所以它使它成为最好的可行构造函数.
| 归档时间: |
|
| 查看次数: |
65 次 |
| 最近记录: |