``` // // main.cpp // 運算符重載(Overloading) // 預設複製構造函數(Default Copy Constructor) // Created by mac on 2019/4/29. // Copyright © 2019年 mac. All rights re ...
//
// 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++的輸出格式設置問題?