nanzh

  博客园 :: 首页 :: 博问 :: 闪存 :: 新随笔 :: 联系 :: 订阅 订阅 :: 管理 ::
  33 随笔 :: 2 文章 :: 5 评论 :: 33301 阅读
< 2025年3月 >
23 24 25 26 27 28 1
2 3 4 5 6 7 8
9 10 11 12 13 14 15
16 17 18 19 20 21 22
23 24 25 26 27 28 29
30 31 1 2 3 4 5

Line类调用Point类的两个对象p1,p2作为其数据成员,计算线段长度

组合类构造函数定义的一般形式为:

  类名::类名(形参表):内嵌对象1(形参表),内嵌对象2(形参表)...

  {类的初始化}

Line例子(课本例子学习):

复制代码
 1 #include<iostream>
 2 #include<cmath>
 3 using namespace std;
 4 class Point{
 5 public:
 6 //隐式内联构造函数(显示inline)
 7     Point(int newX,int newY){
 8         x=newX;
 9         y=newY;
10     }
11 //复制构造函数
12     Point(Point &p);
13     int getX(){return x;}
14     int getY(){return y;}
15 private:
16     int x,y;
17 
18 };
19 //复制构造函数的实现
20 Point::Point(Point &p){
21     x=p.x;
22     y=p.y;
23 }
24 
25 //类的组合
26 class Line{
27 public:
28     Line(Point xp1,Point xp2);
29     Line(Line &q);
30     double getLen(){return len;}
31 private:
32     Point p1,p2;
33     double len;
34 };
35 //组合类的构造函数
36 Line::Line(Point xp1,Point xp2):p1(xp1),p2(xp2){
37     double x=static_cast<double>(p1.getX()-p2.getX());
38     double y=static_cast<double>(p1.getY()-p2.getY());
39     len=sqrt(x*x+y*y);
40 }
41 //组合类的复制构造函数
42 Line::Line(Line &q):p1(q.p1),p2(q.p2){
43     cout<<"calling the copy construct of Line"<<endl;
44     len=q.len;
45 }
46 
47 void fun1(Point p){
48     cout<<"fun1:"<<p.getX()<<","<<p.getY()<<endl;
49 }
50 Point fun2(){
51     Point a(1,2);
52     return a;
53 }
54 int main(){
55 //Point
56     Point a(8,9);
57     Point b=a;
58     cout<<"test point:x="<<b.getX()<<endl;
59     fun1(b);
60     b=fun2();
61     cout<<"test point:x="<<b.getX()<<endl;
62 //Line
63 //point类的复制构造函数被调用了6次
64 //两个对象在Line构造函数进行函数参数形实参结合时+初始化内嵌对象时+复制构造line2时被调>用
65     cout<<"------------"<<endl;
66     Point m(3,4),n(5,6);
67     Line line(m,n);
68     cout<<"line:"<<line.getLen()<<endl;
69     Line line2(line);
70     cout<<"line2:"<<line2.getLen()<<endl;
71 
72     return 0;
73 }
复制代码

 运行结果Ubuntu下g++编译:

 

posted on   深海里的星星nanzh  阅读(12841)  评论(2编辑  收藏  举报
编辑推荐:
· Linux系列:如何用heaptrack跟踪.NET程序的非托管内存泄露
· 开发者必知的日志记录最佳实践
· SQL Server 2025 AI相关能力初探
· Linux系列:如何用 C#调用 C方法造成内存泄露
· AI与.NET技术实操系列(二):开始使用ML.NET
阅读排行:
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!
· 没有Manus邀请码?试试免邀请码的MGX或者开源的OpenManus吧
· 【自荐】一款简洁、开源的在线白板工具 Drawnix
· 园子的第一款AI主题卫衣上架——"HELLO! HOW CAN I ASSIST YOU TODAY
· Docker 太简单,K8s 太复杂?w7panel 让容器管理更轻松!
点击右上角即可分享
微信分享提示