Class, copy constructor, copy assignment
//============================================================================
// Name : classCpConstCpAssign.cpp
// Author : chd
// Version :
// Copyright : Your copyright notice
// Description : Example of copy constructor and copy assignment, C++Ansi-style
//============================================================================
#include <iostream>
using namespace std;
class triple{
float *data;
public:
//constructor
triple(float a, float b, float c);
//destructor
~triple(){delete[] data;}
//copy constructor
triple(const triple& t);
//copy assignment
triple& operator=(const triple& t);
//different classes can share friends
friend triple add(const triple&, const triple&);
//prints the members
void print() const {
cout<<"|"<<data[0]<<"|"<<data[1]<<"|"<<data[2]<<"|"<<endl;
}
};
triple::triple(float a, float b, float c){
data=new float[3];
data[0]=a;
data[1]=b;
data[2]=c;
}
triple::triple(const triple& t){
//here we have to construct/allocate memory first
data=new float[3];
for (int i = 0; i < 3; ++i) {
data[i]=t.data[i];
}
}
triple& triple::operator =(const triple& t){
//memory here already exists
if (this!=&t){
for (int i = 0; i < 3; ++i) {
data[i]=t.data[i];
}
}
return *this;
}
triple add(const triple& t1, const triple& t2){
return triple(t1.data[0]+t2.data[0],t1.data[1]+t2.data[1],t1.data[2]+t2.data[2]);
}
int main() {
triple t1(1,2,3);
triple t2(4,5,6);
triple t3=add(t1,t2);
t3.print();
return 0;
}
Like this:
Like Loading...
Related