C++/Class/Copy Constructor — различия между версиями
Admin (обсуждение | вклад) м (1 версия: Импорт контента...) |
|
(нет различий)
|
Текущая версия на 10:25, 25 мая 2010
A copy constructor to allow StringClass objects to be passed to functions.
#include <iostream>
#include <cstring>
#include <cstdlib>
using namespace std;
class StringClass {
char *p;
public:
StringClass(char *s); // constructor
StringClass(const StringClass &o); // copy constructor
~StringClass() { // destructor
delete [] p;
}
char *get() {
return p;
}
};
StringClass::StringClass(char *s) // "Normal" constructor
{
int l;
l = strlen(s)+1;
p = new char [l];
if(!p) {
cout << "Allocation error\n";
exit(1);
}
strcpy(p, s);
}
StringClass::StringClass(const StringClass &o) // Copy constructor
{
int l;
l = strlen(o.p)+1;
p = new char [l]; // allocate memory for new copy
if(!p) {
cout << "Allocation error\n";
exit(1);
}
strcpy(p, o.p); // copy string into copy
}
void show(StringClass x)
{
char *s;
s = x.get();
cout << s << endl;
}
int main()
{
StringClass a("www.java2s.com"), b("www.java2s.com");
show(a);
show(b);
return 0;
}
copy constructor: X(X&)
#include <iostream>
using namespace std;
class MyClass {
private:
int data;
public:
MyClass(){ }
MyClass(int d){ data = d; }
MyClass(MyClass& a){
data = a.data;
cout << "\nCopy constructor invoked";
}
void display(){ cout << data; }
void operator = (MyClass& a)
{
data = a.data;
cout << "\nAssignment operator invoked";
}
};
int main(){
MyClass a1(37);
MyClass a2;
a2 = a1;
cout << "\na2="; a2.display();
MyClass a3(a1);
cout << "\na3="; a3.display();
return 0;
}
Demonstrating that class objects can be assigned to each other using default memberwise copy
#include <iostream>
using std::cout;
using std::endl;
class Date {
public:
Date( int = 1, int = 1, int = 1990 ); // default constructor
void print();
private:
int month;
int day;
int year;
};
// Simple Date constructor with no range checking
Date::Date( int m, int d, int y )
{
month = m;
day = d;
year = y;
}
// Print the Date in the form mm-dd-yyyy
void Date::print() { cout << month << "-" << day << "-" << year; }
int main()
{
Date date1( 7, 4, 2009 ), date2; // d2 defaults to 1/1/90
cout << "date1 = ";
date1.print();
cout << "\ndate2 = ";
date2.print();
date2 = date1; // assignment by default memberwise copy
cout << "\n\nAfter default memberwise copy, date2 = ";
date2.print();
cout << endl;
return 0;
}