求纠错,函数是可以计算线段长度(line)
#include<iostream>#include<cmath>
using namespace std;
class point
{
public:
point(int xx=0,int yy=0)
{
x=xx;
y=yy;
}
point(point &p);
int getX(){return x;}
int getY(){return y;}
private:
int x,y;
};
point::point(point &p)
{
x=p.x;
y=p.y;
cout<<"calling the copy cnstructor"<<endl;
}
class line {
public:
line(point xp1,point xp2);
line(line &1);
double getlen() {return len;}
private:
point p1,p2;
double len;
};
line::line(point xp1,point xp2):p1(xp1),p2(xp2){
cout<<"calling constructing of line"<<endl;
double x=static_cast<double>(p1.getX()-p2.getX());
double y=static_cast<double>(p1.getY()-p2.getY());
len=sqrt(x*x+y*y);
}
line::line(line &1):p1(1,p1),p2(1,p2){
cout<<"calling the copy constructor of line"<<endl;
len=1.len;
}
int main()
{point myp1(1,1),myp2(4,5);
line line(myp1,myp2);
line line2(line);
cout<<"the length of the line is :"<<line.getlen();
cout<<"the length of the line 2is :"<<line.getlen();
return 0;
} #include<iostream>
#include<cmath>
using namespace std;
class point
{
public:
point(int xx=0,int yy=0)
{
x=xx;
y=yy;
}
point(point &p);
int getX(){return x;}
int getY(){return y;}
private:
int x,y;
};
point::point(point &p)
{
x=p.x;
y=p.y;
cout<<"calling the copy cnstructor"<<endl;
}
class line {
public:
line(point xp1,point xp2);
//c/c++变量命名规则,必须以字母或下划线开头,可以包含字母、数字、下划线
//这里用数字 1 开头作为变量名错误
line(line &l);
double getlen() {return len;}
private:
point p1,p2;
double len;
};
line::line(point xp1,point xp2):p1(xp1),p2(xp2){
cout<<"calling constructing of line"<<endl;
double x=static_cast<double>(p1.getX()-p2.getX());
double y=static_cast<double>(p1.getY()-p2.getY());
len=sqrt(x*x+y*y);
}
//这里用数字 1 开头作为变量名错误,给p1,p2赋值错误
line::line(line &l):p1(l.p1),p2(l.p2){
cout<<"calling the copy constructor of line"<<endl;
len=l.len;
}
int main()
{point myp1(1,1),myp2(4,5);
//变量名不要和类名相同
line line1(myp1,myp2);
line line2(line1);
cout<<"the length of the line is :"<<line1.getlen()<<endl;
cout<<"the length of the line 2is :"<<line2.getlen()<<endl;
return 0;
} 懂了,但大佬,这句程序是什么意思啊line::line(line &l):p1(l.p1),p2(l.p2){ vaety 发表于 2021-3-22 21:10
懂了,但大佬,这句程序是什么意思啊
这句是拷贝构造函数初始化成员变量啊。
line(line & l); 这是拷贝构造函数,
如果成员变量里没有对象变量(某些对象也可以用缺省的拷贝函数),没有指针变量,
是不需要重载(写)拷贝构造函数的,c++会给类一个缺省的拷贝构造函数。
line::line(line &l):p1(l.p1),p2(l.p2)
{
}
相当于
line:line(line &l)
{
p1 = l.p1;
p2 = l.p2;
}
页:
[1]