这个c++程序为何不能这样写?

来源:百度知道 编辑:UC知道 时间:2024/05/13 03:04:46
正确写法:
#include <iostream>
using namespace std;
class Box
{
private:
int width;
int length;
int height;
public:
Box(int w=10,int l=10,int h=10);
void display();
};
void Box::display()
{
cout<<width<<" "<<length<<" "<<height<<endl;
}
Box::Box(int w,int l,int h):width(w),length(l),height(h){}
main()
{
Box box1;
box1.display();
Box box2(12,34);
box2.display();
Box box3(12);
box3.display();
return 0;
}
错误的:
#include <iostream>
using namespace std;
class Box
{
private:
int width;
int length;
int height;
public:
Box(int w=10,int l=10,int h=10);
Box(int w,int l,int h):width(w),length(l),height(h){}
void display();
};
void Box::display()
{
cout<<width<<" "<<leng

错误有这两行.
Box(int w=10,int l=10,int h=10);
Box(int w,int l,int h):width(w),length(l),height(h){}
这两行重复了,如果要在类内的话就应该写成
Box(int w=10,int l=10,int h=10):width(w),length(l),height(h){}

使用域运算符把定义放在类外是很正常的.
而如果像错误的那样会产生二义性编译器就不知怎么编译了.