帮我看看C++程序哪里错了

来源:百度知道 编辑:UC知道 时间:2024/09/21 10:38:39
#include <iostream>
using namespace std;
class box
{ public:
box(int x,int y):chang(x),width(y){}
int swap();
private:
int chang;
int width;
};
int box::swap()
{ return chang*width;
}
int main()
{ box box1(10,20),box2;
box2=box1;
cout<<box1.swap()<<endl;
cout<<box2.swap()<<endl;
return(0);
}

你要把原理搞明白
box box1(10,20),box2;
这句有问题
你这里box(int x,int y):chang(x),width(y){}定义了一个带参数的构造函数
默认的那个就不能用了 如果你还想用 你要自己再定义一个无参构造函数
可以这样改
class box
{ public:
box(int x,int y):chang(x),width(y){}
box(){}
int swap();
private:
int chang;
int width;
};
int box::swap()
{ return chang*width;
}
int main()
{ box box1(10,20),box2;
box2=box1;
cout<<box1.swap()<<endl;
cout<<box2.swap()<<endl;
return(0);
}

#include <iostream>
using namespace std;
class box
{
public:
box(int x,int y):chang(x),width(y){}
int swap();
private:
int chang;
int width;
};
int box::swap()
{
return chang*width;
}
int main()
{
box box1(10,12),box2(21,22);
box2=box1;
cout<<box1.swap()<<endl;
cout<<box2.swap()<<endl;
return