C++构造函数使用的多种方法

百般思念 提交于 2020-03-30 16:44:34
// 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() << '\n';
  cout << "bar circumference: " << bar.circum() << '\n';
  cout << "bazcircumference: " << baz.circum() << '\n';
  cout << "qux circumference: " << qux.circum() << '\n';
  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.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!