zoukankan      html  css  js  c++  java
  • C++构造函数使用的多种方法

    // classes and uniform initialization
    #include <iostream>
    using namespace std;
    
    class Circle {
        double radius;
      public:
        Circle(double r) { radius = r; }
        double circum() {return 2*radius*3.14159265;}
    };
    
    int main () {
      Circle foo (10.0);   // functional form
      Circle bar = 20.0;   // assignment init.
      Circle baz {30.0};   // uniform init.
      Circle qux = {40.0}; // POD-like
    
      cout << "foo's circumference: " << foo.circum() << '
    ';
      cout << "bar circumference: " << bar.circum() << '
    ';
      cout << "bazcircumference: " << baz.circum() << '
    ';
      cout << "qux circumference: " << qux.circum() << '
    ';
      return 0;
    }
    

      

    Rectangle rectb;   // default constructor called
    Rectangle rectc(); // function declaration (default constructor NOT called)
    Rectangle rectd{}; // default constructor called 
    

      

    Member initialization in constructors
    When a constructor is used to initialize other members, these other members can be initialized directly, without resorting to statements in its body. This is done by inserting, before the constructor's body, a colon (:) and a list of initializations for class members. For example, consider a class with the following declaration:

     

    class Rectangle {
    int width,height;
    public:
    Rectangle(int,int);
    int area() {return width*height;}
    };
    

    The constructor for this class could be defined, as usual, as:

    Rectangle::Rectangle (int x, int y) { width=x; height=y; }
    

    But it could also be defined using member initialization as:

    Rectangle::Rectangle (int x, int y) : width(x) { height=y; }
    

    Or even:

    Rectangle::Rectangle (int x, int y) : width(x), height(y) { }
    

    Note how in this last case, the constructor does nothing else than initialize its members, hence it has an empty function body.

  • 相关阅读:
    写给自己的2020年总结
    docker镜像与docker容器
    docker安装&docker简介
    windows 安装linux子系统
    typora设置图床
    让Mysql插入中文
    pip 换源
    Unity中如何将一个场景(Scene)的Light Settings复制给另一个场景
    Windows API开发
    【C#】判断字符串中是否包含指定字符串,contains与indexOf方法效率问题
  • 原文地址:https://www.cnblogs.com/CodeWorkerLiMing/p/11074537.html
Copyright © 2011-2022 走看看