赋值构造函数
- 如果没有定义赋值构造函数,编译器会自动定义“合成的赋值构造函数”,
与其他合成的构造函数,是“浅拷贝”(又称为“位拷贝”)。
定义:
Human& operator=(const Human& other);
实现:
Human& Human::operator=(const Human& other){
//当other = other时;
if (this == &other) return *this;
//假如 f1 = f2;
//自动调用, f1.operator=(f2)
this->name = other.name;
this->age = other.age;
this->sex = other.sex;
strcpy_s(this->addr,ADDR_LEN, other.addr);
//返回对象的引用,是为了做链式处理: f1 = f2 = f3;
return *this;
}
调用:
对象赋值时自动调用
//调用赋值构造函数
lisi = zhangsan;
Human.h
#pragma once
#include <string>
#include <iostream>
#include <Windows.h>
using namespace std;
class Human {
public:
Human();
~Human();
Human(string name, int age, string sex);
//定义了一个赋值构造函数
Human& operator=(const Human& other);
string getName() const;
string getSex() const;
int getAge() const;
const char* getAddr()const;
void setAddr(char* addr);
void description() const;
private:
string name; //姓名
string sex; //性别
int age; //年龄
char* addr; //地址
};
Human.cpp
#include "Human.h"
#define ADDR_LEN 64
Human::Human() {
name = "无名";
sex = "未知";
age = 18;
const char* addr_s = "China";
addr = new char[ADDR_LEN];
strcpy_s(addr, ADDR_LEN, addr_s);
}
Human::Human(string name, int age, string sex) {
this->age = age;
this->name = name;
this->sex = sex;
const char* addr_s = "China";
addr = new char[ADDR_LEN];
strcpy_s(addr, ADDR_LEN, addr_s);
}
Human& Human::operator=(const Human& other){
//当other = other时;
if (this == &other) return *this;
//假如 f1 = f2;
//自动调用, f1.operator=(f2)
this->name = other.name;
this->age = other.age;
this->sex = other.sex;
strcpy_s(this->addr,ADDR_LEN, other.addr);
//返回对象的引用,是为了做链式处理: f1 = f2 = f3;
return *this;
}
string Human::getName() const {
return name;
}
string Human::getSex() const {
return sex;
}
int Human::getAge() const {
return age;
}
const char* Human::getAddr() const{
return addr;
}
void Human::setAddr(char* addr){
if (!addr) return;
strcpy_s(this->addr, ADDR_LEN, addr);
}
main.cpp
#include "Human.h"
using namespace std;
void showMsg(const Human &man1, const Human& man2) {
cout << "张三地址: " << man1.getAddr() << endl;
cout << "李四地址: " << man2.getAddr() << endl;
}
int main(void) {
Human zhangsan("张三", 18, "男");
Human lisi;
//调用赋值构造函数
lisi = zhangsan;
cout << "张三修改地址前" << endl;
showMsg(zhangsan, lisi);
zhangsan.setAddr((char*)"新加坡");
cout << "张三修改地址后" << endl;
showMsg(zhangsan, lisi);
system("pause");
return 0;
}