3
// Case A
class Point {
private:
    int x;
    int y;
public:
    Point(int i = 0, int j = 0);  // Constructor
};

Point::Point(int i, int j)  {
    x = i;
    y = j;
    cout << "Constructor called";
}

// Case B:
class Point {
private:
    int x;
    int y;
public:
    Point(int i, int j);  // Constructor
};

Point::Point(int i = 0, int j = 0)  {
    x = i;
    y = j;
    cout << "Constructor called";
}

问题> Case A 和 Case B 用 VS2010 编译都没有问题。

原来我假设只有案例 A 有效,因为我记得应该在声明函数的地方引入默认参数,而不是在其定义的位置引入。有人可以纠正我吗?

谢谢

4

1 回答 1

0

如果将默认参数放入方法定义中,那么只有看到定义的人才能使用默认参数。唯一的问题是如果你尝试这样的事情:

public:
    Point(int i = 0, int j = 0);

(...)

Point::Point(int i = 0, int j = 0) { ... }

然后你会得到一个构建时错误。

// 编辑:但我很好奇 Mark B. 会发现什么,正如您问题下的评论中提到的那样。

// EDIT2:而且显然clang编译器不喜欢案例B。

于 2013-08-20T18:43:02.100 回答