zoukankan      html  css  js  c++  java
  • c++组合类构造函数顺序

    #include <iostream>
    #include <cmath>
    using namespace std;
     
    class Point{
    	private:
    		int x, y;
    	
    	public:
    		Point(int a = 0, int b = 0)
    		{
    			x = a; y = b;
    			cout << "Point construction: " << x << ", "<< y << endl;
    		}
    		Point(Point &p) // copy constructor,其实数据成员是int类型,默认也是一样的 
    		{
    			x = p.x;
    			y = p.y;
    			cout << "Point copy construction: " << x << ", "<< y << endl; 
    		}
    		int getX()
    		{
    			return x;
    		}
    		int getY()
    		{
    			return y;
    		}
    }; 
     
    class Line{
    	private:
    		Point start, end;
    	
    	public:
    		Line(Point pstart, Point pend)
                        :start(pstart), end(pend) // 组合类的构造函数对内前对象成员的初始化必须采用初始化列表形式
    		{
    			cout << "Line constructior " << endl;
    		}
    		float getDistance()
    		{
    			double x = double(end.getX()-start.getX());
    			double y = double(end.getY()-start.getY());
    			return (float)(sqrt)(x*x+y*y);
    		}
    };
     
    int main()
    {
    	Point p1(10,20),p2(100,200);
    	Line line(p1,p2);
    	cout << "The distance is: "<<line.getDistance()<<endl; return 0;
    }
    

    输出结果:

    Point construction: 10, 20
    Point construction: 100, 200
    Point copy construction: 100, 200
    Point copy construction: 10, 20
    Point copy construction: 10, 20
    Point copy construction: 100, 200
    Line constructior
    The distance is: 201.246
    

    Line line(p1,p2);这一行代码在vs下面直接跳到point的复制构造函数,然后才进入line的构造函数的初始化列表,并再次进入point的复制构造函数

  • 相关阅读:
    Swing中如何比较好的判断鼠标左键双击
    学习rsyslog
    学习rsync
    在线手册
    Linux开源镜像站大全
    Linux命令
    Android使用sqlite数据库的使用
    Android学习笔记-listview实现方式之BaseAdapter
    Android学习笔记-保存数据的实现方法2-SharedPreferences
    Android学习笔记-获取手机内存,SD卡存储空间。
  • 原文地址:https://www.cnblogs.com/working-in-heart/p/12089233.html
Copyright © 2011-2022 走看看