重载赋值运算符
//
// main.cpp
// 运算符重载(Overloading)
// 默认复制构造函数(Default Copy Constructor)
// Created by mac on 2019/4/29.
// Copyright © 2019年 mac. All rights reserved.
// 析构函数是一个成员函数,当对象被销毁时,该函数被自动调用。
// 析构函数是具有与类相同名称的公共(public)成员函数
// 构造函数私有化之后就无法在类外生成对象。
// 结构体能否支持继承
// 复制构造函数只能在创建对象并在初始化对象时起作用,复制构造函数不能在赋值(Assignment)中调用。
// 复制构造函数开始有点遗忘了。
#include <iostream>
#include <iomanip>
using namespace std;
class NumberArray{
private:
double *aPtr;
int arraySize;
public:
NumberArray & operator= (const NumberArray &right);//重载赋值运算符= (重载运算符函数)
~NumberArray(){if (arraySize>0) delete []aPtr;}
NumberArray(const NumberArray &);
NumberArray(int size,double value);
void print()const;
void setValue(double value);
};
//重载赋值运算符=
NumberArray & NumberArray::operator=(const NumberArray &right){
if(this!=&right){
if(this->arraySize>0){
delete [] aPtr;
}
this->arraySize=right.arraySize;
aPtr=new double[this->arraySize];
for (int index=0; index<arraySize; ++index) {
this->aPtr[index]=right.aPtr[index];
}
}
return *this;
}
//复制构造函数
NumberArray::NumberArray(const NumberArray &obj){
if(this->arraySize>0){
delete [] aPtr;
}
this->arraySize=obj.arraySize;
aPtr=new double[this->arraySize];
for (int index=0; index<this->arraySize; ++index) {
aPtr[index]=obj.aPtr[index];
}
}
//构造函数
NumberArray::NumberArray(int size,double value){
this->arraySize=size;
aPtr=new double[arraySize];
setValue(value);
}
//用value值初始化整个数组
void NumberArray::setValue(double value){
for (int index=0; index<this->arraySize; ++index) {
aPtr[index]=value;
}
}
//打印整个数组
void NumberArray::print()const{
for (int index=0;index<arraySize; ++index) {
cout<<aPtr[index]<<" ";
}
}
int main(int argc, const char * argv[]) {
NumberArray first(3,10.5);
NumberArray second(5,20.5);
cout<<setprecision(2)<<fixed<<showpoint;
cout<<"First object's data is ";
first.print();
cout<<endl<<"Second object's data is ";
second.print();
//调用重载运算符
cout<<"\nNow we will assign the second object "<<"to the first."<<endl;
first=second;
//打印赋值以后两个对象里面的新的值
cout<<"First object's data is ";
first.print();
cout<<endl<<"Second object's data is ";
second.print();
return 0;
}
运行结果:
First object's data is 10.50 10.50 10.50
Second object's data is 20.50 20.50 20.50 20.50 20.50
Now we will assign the second object to the first.
First object's data is 20.50 20.50 20.50 20.50 20.50
Second object's data is 20.50 20.50 20.50 20.50 20.50 Program ended with exit code: 0
Tips
- C++的输出格式设置问题?
未经本人准许,禁止转载.