31 C++ 基础—this 指针和复制构造函数

1. this 指针

this 指针是指向类对象的指针,

  1. 隐式使用this指针,编译器完成
#include "Student.h"
#include <string>

string Student :: getName() {
    return name;
}

void Student ::setName(string vaule){
    name = vaule;
}
  1. 显式使用this指针
#include "Student.h"
#include <string>

// 显示使用 this指针
string Student :: getName() {
    return (*this).name;
}

void Student ::setName(string vaule){
    this->name = vaule;
}

2. 复制构造函数

复制构造函数是一种特殊的构造函数,在创建一个新的对象是将其他对象作为参数,编译器将会调用复制构造函数。不提供默认构造函数。默认构造函数的内部各个成员变量赋值。创建之后,新对象是老对象的副本,二者值相同,但是具有不同的存储空间。形式如 Student(Student& mStudent)

// 复制构造函数,注意是传递引用
// 如果去除引用 Student::Student(Student mStudent){,则变成传递对象,
// 此时对象会被创新创建,程序开销增多,
// 这就是为什么我们使用复制构造函数的原因之一
Student::Student(Student& mStudent){
    name = mStudent.name;
}

调用复制构造函数的时机
1. 以其他对象作为参数创建对象时

#include <iostream>
#include "Student.h"

using namespace std;

int main() {
    // 构造函数
    Student mStudent("李白");

    // 复制构造函数
    Student mS(mStudent);

    cout<<"Name = "<<mS.getName()<<endl;

    return 0;
}
  1. 复制构造函数定义

Student.h

#ifndef STUDENT_H
#define STUDENT_H

#include <iostream>
#include <string>

using namespace std;

class Student {
public:
    // 复制构造函数
    Student(Student& mStudent);

    Student(string vaule);

    void setName(string vaule);
    string getName();

private:
    string name;
};
#endif
  1. 复制构造函数实现
#include "Student.h"
#include <string>

// 复制构造函数
Student::Student(Student& mStudent){
    name = mStudent.name;
}

// 构造函数
Student::Student(string vaule){
    name = vaule;
}

string Student :: getName() {
    return name;
}

void Student ::setName(string vaule){
    name = vaule;
}

猜你喜欢

转载自blog.csdn.net/su749520/article/details/80318775
今日推荐