前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >C++构造/析构函数

C++构造/析构函数

作者头像
用户2929716
发布2018-08-23 13:17:56
6720
发布2018-08-23 13:17:56
举报
文章被收录于专栏:流媒体流媒体

构造函数初始化列表

当类的成员变量中存在类时候,同时成员类没有无参或默认构造函数,在创建该类的对象时候会出错。这是需要使用初始化列表。将需要的成员变量进行初始化。

  • 初始化列表的初始化顺序是按成员变量的定义顺序进行初始化,最后执行到构造函数内部。
  • 析构函数的执行顺序与构造时候相反。
代码语言:javascript
复制
//Rect.h
#include "Point.h"
class Rect {
private:
   int index;
   Point p2;
   Point p1;
public:
   Rect(int index, int x1, int x2);
   ~Rect();
   void print();
};

//Rect.cpp
Rect::Rect(int index, int x1, int x2):p1(x1,0,"name is p1"),p2(x2,0,"name is p2") {
   this->index=index;
}

拷贝构造函数调用时机

  • 一个对象赋值给另一个对象 Point p2 = p1;
  • 构造函数中作为参数传入 Point p3(p1);
  • 函数调用时,存在类作为参数,实参到形参。 void printPoint(Point point) { cout << point.getX() << " " << point.getY() << endl; }
  • 函数返回值为对象时候(编译器会做优化,可能不会调用)。 Point getPoint() { Point p(10, 20); return p; }

示例

Point.h

代码语言:javascript
复制
class Point {
private:
    int x;
    int y;
public:
    Point(int x, int y);

    Point(int x);

    Point();

    int getX() const;

    void setX(int x);

    int getY() const;

    void setY(int y);

    virtual ~Point();

    Point(const Point&);
};

Point.cpp

代码语言:javascript
复制
#include "iostream"
#include "Point.h"

using namespace std;

int Point::getX() const {
    return x;
}

void Point::setX(int x) {
    Point::x = x;
}

int Point::getY() const {
    return y;
}

void Point::setY(int y) {
    Point::y = y;
}

Point::Point(int x, int y) : x(x), y(y) {
    this->x = x;
    this->y = y;
    cout << "Point(x=" << x << ",y=" << y << ")" << endl;
}

Point::Point(int x) : x(x) {
    this->x = x;
    cout << "Point(x=" << x << ")" << endl;
}

Point::Point() {
    cout << "Point()" << endl;
}

Point::~Point() {
    cout << "~Point()" << endl;
}

Point::Point(const Point &point) {
    this->x = point.x + 100;
    this->y = point.y + 100;
    cout << "Point(const Point &point)" << endl;
}

结果:

代码语言:javascript
复制
Point(x=1,y=2)
----
Point(const Point &point)
----
Point(const Point &point)
----
Point(const Point &point)
101 102
~Point()
----
Point(x=1,y=2)
~Point()
~Point()
~Point()
~Point()

浅拷贝、深拷贝

  • 默认的copy构造函数和赋值操作是浅拷贝。值拷贝成员变量的值。当成员变量中存在指针时候,释放内存空间时,会出现野指针问题。 这时候需要重写copy构造函数。如:
代码语言:javascript
复制
Point::Point(const Point &point) {
    this->x = point.x + 100;
    this->y = point.y + 100;
    if (point.getName() != NULL) {
        int len = strlen(point.getName());
        this->name = (char *) malloc((sizeof(char)) * (len + 1));
        strcpy(this->name, point.getName());
    }
    cout << "Point(const Point &point)" << endl;
}
本文参与 腾讯云自媒体分享计划,分享自作者个人站点/博客。
原始发表:2017.08.09 ,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体分享计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • 构造函数初始化列表
  • 拷贝构造函数调用时机
  • 示例
  • 浅拷贝、深拷贝
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档