C++构造函数形参问题!

来源:百度知道 编辑:UC知道 时间:2024/06/15 13:30:13
以下程序不通过!是因为Rectangle构造函数的形参不可以用Point来定义吗??
#include<iostream>
using namespace std;
class Point
{ private:
int x,y;
public:
Point(int a,int b){x=a;y=b;}
void Display(){cout<<x<<","<<y<<endl;}
};
class Rectangle
{ private:
Point A,B;
int L;
public:
Rectangle(Point C,Point D,int l)
{ A=C;
B=D;
L=l;}
void Display()
{ A.Display();
B.Display();
cout <<"L="<<L<<endl;
}
};
void main()
{ Point A(10,2),B(20,2);
Rectangle rect(A,B,7);
rect.Display();
getchar();
}

//* 本结果在编译器下编译通过.
#include<iostream>
using namespace std;
class Point
{
private:
int x,y;
public:
Point(int a,int b){x=a;y=b;}
//* 构造函数重载.
Point(Point& pt)
{
x = pt.x;
y = pt.y;
}
void Display(){cout<<x<<","<<y<<endl;}
};
class Rectangle
{ private:
Point A,B;
int L;
public:
Rectangle(Point C,Point D,int l) : A(C), B(D)
{
A=C;
B=D;
L=l;}
void Display()
{ A.Display();
B.Display();
cout <<"L="<<L<<endl;
}
};

int _tmain(int argc, _TCHAR* argv[])
{
Point A(10,2),B(20,2);
Rectangle rect(A,B,7);
rect.Display();
getchar();
return 0;
}
C++基础知识不强.你的Point A,B是在Rectangle之前构造的,你没有提供默认构造函数,又没有给它传递参数,当然不行了.
总之,你这个问题可以有N种解.我只给出其中一种.

Rectangle (Point C, Point D, int l): A(C)