简体   繁体   English

C ++函数默认参数的位置

[英]Location of C++ function default parameters

// 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";
}

Question> Both Case A and Case B compile without problems with VS2010. 问题>案例A和案例B编译都没有VS2010的问题。

Original I assume only Case A works because I remember that the default parameters should be introduced in the place where the function is declared rather than the location of its definition. 原文我假设只有案例A有效,因为我记得应该在声明函数的地方而不是其定义的位置引入默认参数。 Can someone correct me on this? 有人可以纠正我吗?

Thank you 谢谢

If you put the default parameters into the method definition, then only those who see the definition would be able to use the default parameters. 如果将默认参数放入方法定义中,则只有看到定义的人才能使用默认参数。 The only problem would be if you tried something like this: 唯一的问题是如果你尝试过这样的事情:

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

(...)

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

Then you would get a build-time error. 然后你会得到一个构建时错误。

// EDIT: But I'm curious what Mark B. will find as mentioned in a comment under your question. //编辑:但我很好奇Mark B.会在你的问题评论中提到的内容。

// EDIT2: And also apparently clang compiler doesn't like Case B. // EDIT2:显然clang编译器也不喜欢Case B.

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM