温馨提示×

温馨提示×

您好,登录后才能下订单哦!

密码登录×
登录注册×
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》

C++11中委托构造函数如何使用

发布时间:2021-06-21 18:48:46 来源:亿速云 阅读:208 作者:Leah 栏目:大数据

这篇文章将为大家详细讲解有关C++11中委托构造函数如何使用,文章内容质量较高,因此小编分享给大家做个参考,希望大家阅读完这篇文章后对相关知识有一定的了解。

C++11之前的状况

构造函数多了以后,几乎必然地会出现代码重复的情况,为了避免这种情况,往往需要另外编写一个初始化函数。例如下面的Rect类:

struct Point{
   int x;
   int y;
};
struct Rect{
   Rect(){
       init(0, 0, 0, 0, 0, 0);
   }
   Rect(int l, int t, int r, int b){
       init(l, t, r, b, lc, fc, 0, 0);
   }
   Rect(int l, int t, int r, int b,
         int lc, int fc){
       init(l, t, r, b, lc, fc);
   }
   Rect(Point topleft, Point bottomright){
       init(topleft.x, topleft.y,
       bottomright.x, bottomright.y,
        0, 0);
   }
   init(int l, int t, int r, int b,
         int lc, int fc){
       left = l; top = t;        
       right = r; bottom = b;
       line_color = lc;
       fill_color = fc;
       //do something else...
   }
   int left;
   int top;
   int right;
   int bottom;
   int line_color;
   int fill_color;    
};

数据成员初始化之后要进行某些其他的工作,而这些工作又是每种构造方式都必须的,所以另外准备了一个init函数供各个构造函数调用。

这种方式确实避免了代码重复,但是有两个问题:

  1. 没有办法不重复地使用成员初始化列表

  2. 必须另外编写一个初始化函数。

C++11的解决方案

C++11扩展了构造函数的功能,增加了委托构造函数的概念,使得一个构造函数可以委托其他构造函数完成工作。使用委托构造函数以后,前面的代码变成下面这样:

struct Point{
   int x;
   int y;
};
struct Rect{
   Rect()
       :Rect(0, 0, 0, 0, 0, 0)
   {
   }
   Rect(int l, int t, int r, int b)
       :Rect(l, t, r, b, 0, 0)
   {
   }
   Rect(Point topleft, Point bottomright)
       :Rect(topleft.x, topleft.y,
            bottomright.x, bottomright.y,
            0, 0)
   {
   }
   Rect(int l, int t, int r, int b,
        int lc, int fc)
       :left(l), top(t), right(r),bottom(b),
         line_color(lc), fill_color(fc)
   {
       //do something else...
   }
   int left;
   int top;
   int right;
   int bottom;
   int line_color;
   int fill_color;
};

关于C++11中委托构造函数如何使用就分享到这里了,希望以上内容可以对大家有一定的帮助,可以学到更多知识。如果觉得文章不错,可以把它分享出去让更多的人看到。

向AI问一下细节

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

c++
AI