c++ newclass
#include<iostream>
using std::endl;
using std::ostream;
using std::cout;
using std::istream;
using std::cin;
class My
{
friend ostream& operator<<(ostream &os, My &my);
friend istream& operator>>(istream &os, My &my);
public:
My(double _a, double _b):a(_a),b(_b){ }
My()
{
}
private:
double a,b;
};
int main()
{
My m1(1.1,2.2);
My m2(3.3,4.4);
//cout 은 ostream의 객체
//cin 은 istream의 객체
//객체 출력
//cout.operator<<(m1) //멤버함수에 의한 오버로딩 해결 불가능
//operator<<(cout,m1); //전역함수에 의한 오버로딩으로 해결
cout<<m1<<endl;
cout<<m2<<endl;
My m3;
cout<<"실수 두개 입력 : ";
cin>>m3;//operator>>(cin,m3)
cout<<"m3 "<<m3<<endl;
return 0;
}
//////////////////////////////////////////////////
//전역함수
ostream& operator<<(ostream &os, My &my)
{
os<<my.a<<" "<<my.b;
return os;
}
istream& operator>>(istream &is, My &my)
{
is>>my.a>>my.b;
return is;
}
///////////////////////////////////////////////
int *p;
p=new int;
delete p;
////////////////////////////////////////////////
int *p;
p=new int[100];
delete []p;
///////////////////////////////////////////////
int *p[3];
p[0]=new int;
delte p[0];
//////////////////////////////////////////////
int *p[3]
p[0] = new int[100];
delete [] p[0];
//////////////////////////////////////////////
#include<iostream>
using std::cout;
using std::cin;
using std::endl;
using std::ostream;
using std::istream;
class MyString
{
friend ostream& operator<<(ostream &os,MyString &ms);
friend istream& operator>>(istream &is, MyString &ms);
public:
MyString();
MyString(char *pC);
~MyString();
private:
char *ptr;
};
MyString::MyString()
{
//#define NULL 0, 포인터가 가리키는 값이 없음
ptr=NULL;
cout<<"인수를 받지 않는 생성자 호출\n";
}
MyString::MyString(char *pC)
{
ptr = new char[strlen(pC)+1];//동적할당
strcpy(ptr,pC);//문자열 복사
}
MyString::~MyString()
{
if(ptr!=NULL)
{
delete []ptr;//동적 할당 해제
cout<<"동적 메모리 할당 해체\n";
}
}
ostream& operator<<(ostream &os,MyString &ms)
{
if(ms.ptr!=NULL)
{
os<<ms.ptr<<endl;
}
return os;
}
istream& operator>>(istream &is, MyString &ms)
{
char temp[1024];
is>>temp;
ms.ptr= new char[strlen(temp)+1];
strcpy(ms.ptr,temp);
return is;
}
int main()
{
MyString s1 = "hello world";
MyString s2 = "time and tied wait for no man";
MyString s3;
cout<<"s1="<<s1<<endl;
cout<<"s2="<<s2<<endl;
cout<<"문자열입력 : ";
cin>>s3; // operator>>(cin,s3);
cout<<"s3="<<s3<<endl;
return 0;
}