| 12
 3
 4
 5
 6
 7
 8
 9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
 100
 101
 102
 103
 104
 105
 106
 107
 108
 109
 110
 111
 112
 113
 
 |  
// test5.cpp : Defines the entry point for the console application.
//
 
#include "stdafx.h"
#include <iostream.h>
#include <string.h>
 
#define  DEBUG
class test
{
int x;
char * name;
public:
//constructeurs
	test(int c1=0, const char * c2="?");
	test(const test &);
	test operator + (const test &);
 
//Comment faire un operateur + qui renvoie un objet de type test ??
	test & operator = (test &);
    void showName();
    void swap(test & );
 
	//destructeurs
	~test()
	{
		cout<<"destructeur";
		showName();
		delete name;
	}
};
 
test::test(int c1,const char * c2)
{
 name=new char[strlen(c2)+1];
 
 strcpy(name, c2);
 
 x=c1;
#ifdef DEBUG
 cout <<"constructeur par defaut" ;
#endif
 showName();
}
 
 
test::test(const test & obj)
{
 int len;
 len=strlen(obj.name) + strlen("copie ");
 name=new char[len +1];
 strcpy(name,"copie ");
 strcat(name,obj.name);
#ifdef DEBUG
 cout <<"constructeur par recopie";
 showName();
#endif
  x= obj.x;
 
}
 
test test::operator+(const test & obj)
{ 
  test tmp;
  tmp.x=x+ obj.x;
  return tmp;
}
 
 
 
test & test::operator = (test & obj)
{
 int len;
 cout << "sizeof" << sizeof(obj.name) << " strlen" << strlen(obj.name) <<"\n";
 
 len=strlen(obj.name) + strlen("op= ");
 delete [] name;
  name = new char[len+1];  
#ifdef DEBUG 
 cout << "fonction operator =\n";
#endif
 strcpy(name,"op= ");
 strcat(name,obj.name);
 x=obj.x;
 return *this; 
}
 
 
 
void test::showName()
{
cout <<" nom : " <<  name << endl;
}
 
int main(int argc, char* argv[])
{
 
 test a=test (5,"a");
 test b(10,"b");
 test c(20,"c");
 test somme(10,"somme");
 c=a;
#ifdef DEBUG
 cout<<"avant adition\n";
#endif
 somme = c + a;
#ifdef DEBUG
 cout<<"après adition\n";
#endif
 
 return 0;
} | 
Partager