class D{
int x,y;
public:
D(){
x=0;
y=0;
}
};和
class D{
int x,y;
public:
D(int x=0,int y=0){
}
};的区别

C++构造函数初始化的问题
- 写回答
- 好问题 0 提建议
- 关注问题
- 邀请回答
-
1条回答 默认 最新
- bostonAlen 2022-11-08 23:17关注
这个例子可能能帮助你
#include <iostream> using namespace std; class Box { public: Box(int h = 2, int w = 2, int l = 2);//在声明构造函数时指定默认参数 int volume(); private: int height, width, length; }; Box::Box(int h, int w, int len) {//在定义函数时可以不指定默认参数 height = h; width = w; length = len; } int Box::volume() { return height * width*length; } int main() { Box box1(1);//不指定第2、3个实参 cout << "box1's volume: " << box1.volume() << endl; Box box2(1, 3);// 不指定第3个实参 cout << "box2's volume: " << box2.volume() << endl; Box box3; cout << "box3's volume:" << box3.volume() << endl; return 0; }
本回答被题主选为最佳回答 , 对您是否有帮助呢?解决 无用评论 打赏 举报