gpt4 book ai didi

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

转载 作者:太空狗 更新时间:2023-10-29 23:17:24 24 4
gpt4 key购买 nike

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

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

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

谢谢

最佳答案

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

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

(...)

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

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

//编辑:但我很好奇 Mark B. 会在您的问题下的评论中找到什么。

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

关于c++ - C++ 函数默认参数的位置,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18342472/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com