'lab/c++'에 해당되는 글 10건
- 2008.09.04 c++ newclass
- 2008.09.03 c++ 연산자 중복오버로딩 , friend 함수
- 2008.09.02 c++ operator_overloading
- 2008.09.01 c++ . object pointer, dynamic binding, virtural
- 2008.08.29 product
- 2008.08.29 product
- 2008.08.28 c++ . 상속-1 . inheritance
- 2008.08.27 c++ pointer object arry
- 2008.08.25 c++ . static
- 2008.08.22 c++ this . const .
#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;
}
#include<iostream>
using std::cout;
using std::cin;
using std::endl;
//////////////////////////////////////////////////////////////////////
class My
{
// 프렌드 함수 - 클래스와 전역 함수가 밀접한 관계를 갖는 경우 선언
// 전역함수는 클래스의 모든 멤버를 자유롭게 접근
friend My operator+(int n, My &my); //프렌드 함수
public:
My(double _a=0, double _b=0);
My operator+(int c);
void Out();
private:
double a,b;
};
My::My(double _a, double _b):a(_a),b(_b)
{ }
My My::operator+(int c)
{
My temp ;
temp.a=a+c;
temp.b=b+c;
return temp;
}
void My::Out()
{
cout<<"a="<<a<<" "<<"b="<<b<<endl;
}
//////////////////////////////////////////
My operator+(int n, My &my)
{
My temp;
temp.a = n + my.a;
temp.b = n + my.b;
return temp;
}
int main()
{
My m1(1.1,2.2);
My m2;
m2 = m1+10; // m1.operator+(10);
m1.Out();
m2.Out();
My m3;
//좌측 피연산자가 기본자료형이 되는 경우 클래스의 멤버 함수 호출 불가
m3 = 10+m1; // m1.operator+(10);
m3.Out();
return 0;
}
A1 + A2
1. 멤버 함수 : 좌측 호출 객체 + 우측 인수 -> A1.operator+(A2)
2. 전역 함수 : 좌측 인수 + 우측 (인수)객체 -> operator+(a1+a2);
++A
1. 멤버 함수 : 호출 객체
a.operator++();
2. 전역 함수 : 인수
operator++(a);
#include<iostream>
using std::cout;
using std::cin;
using std::endl;
/////////////////////////////////////////클래스 선언
class Point
{
//프렌드 함수 선언
friend Point& operator--(Point &pbar);
public:
Point(int _a, int _b);
Point& operator++();
void Show();
private:
int a, b;
};
///////////////////////////////////////외부 정의
Point::Point(int _a, int _b):a(_a),b(_b)
{
}
//Point& 레퍼런스로 리턴 시 복사본은 생성되지 않는다.( 참고 :Point* 주소로 받겠다.)
Point& Point::operator++()
{
++a;
++b;
return *this; // this (주소) --> *this (주소가 가리키는 값)
}
/// this 호출한 객체의 주소저장되어있다!!!!!!!!!!!
void Point::Show()
{
cout<<"a = "<<a<<" " <<" b = "<<b<<endl;
}
/////////////////////////////////////////전역 함수
Point& operator--(Point &pbar)
{
--pbar.a;
--pbar.b;
return pbar;
}
int main()
{
Point p(5,6);
++++p;
p.Show(); //p.operator++();
------p;
p.Show(); //operator--(p);
return 0;
}
#include<iostream>
using std::cout;
using std::cin;
using std::endl;
//////////////////////////////////////////////
class MyClass
{
public:
MyClass operator+(MyClass &my);// 덧셈 함수
MyClass(double _a=0, double _b=0);//디폴트 파라미터를 갖는 생성자( 인수없이 객체 생성시
에 필요)
void Out();//출력 함수
private:
int a,b;
};
//////////////////////////////////////////////
MyClass::MyClass(double _a, double _b):a(_a),b(_b){}
MyClass MyClass::operator+(MyClass &my)
{
MyClass temp;
temp.a = a+my.a;
temp.b = b+my.b;
return temp;
}
void MyClass::Out()
{
cout<<a<<" " <<b<<endl;
}
int main()
{
MyClass m1(1.1,2.2);
MyClass m2(1.1,2.2);
MyClass m3;
// m3= m1.Add(m2);
m3= m1+m2;//내부적으로 변환된 코드 ---> m1.operator+(m2)
//좌측 피연산자 : 호출객체 , 함수 이름: operator[연산자], 우측 피연산자 : 인수
m1.Out();
m2.Out();
m3.Out();
return 0;
}
#include<iostream>
using std::cout;
using std::endl;
///////////////////////////////////////////
class Point
{
public:
//생성자
Point(int _a=0,int _b=0);
//연산자 오버로딩 [==]
bool operator==(Point &po);
//연산자 오버로딩 [+]
Point operator+(Point &pl);
//연산자 오버로딩 [+=]
Point operator+=(Point &pp);
void show()const;
private:
int a,b;
};
///////////////////////////////////////////
Point::Point(int _a,int _b):a(_a),b(_b){}
bool Point::operator==(Point &po)
{
if(a==po.a&&b==po.b)
return true;
else
return false;
}
Point Point::operator+(Point &pl)
{
Point temp;
temp.a=a+pl.a;
temp.b=b+pl.b;
return temp;
}
void Point::show()const
{
cout<<"a : "<<a<<endl;
cout<<"b : "<<b<<endl;
}
Point Point::operator+=(Point &pp)
{
a+=pp.a;
b+=pp.b;
return *this;
}
int main()
{
Point p1(2,1);
Point p2(2,1);
if(p1==p2)
cout<<"같다"<<endl;
else
cout<<"다르다"<<endl;
Point p3;
p3=p1+p2;
p3.show();
p2+=p3;
p2.show();
p1+=p2+=p3;
p1.show();
return 0;
}
#include<iostream>
using std::cout;
using std::cin;
using std::endl;
//////////////////////////////////////// class 선언부
//추상 클래스 - 순수 가상 함수를 한개 이상 포함한 클래스
//절대로 객체 생성이 불가능 - 자식을 위해 틀을 만드는 클래스
class Animal
{
public:
Animal()
{
}
//순수 가상함수 - 반드시 오버라이딩해서 써야하는 함수
//선언부만 있고 정의부는 없는 함수
virtual void Speak()=0;
virtual void Walk();
//부모 클래스에 가상 함수가 포함되었다면 반드시 소멸자를 가상으로 추가해야한다.
virtual ~Animal()
{
cout<<"~Animal소멸자"<<endl;
}
};
class Dog : public Animal
{
public:
virtual void Speak();
~Dog()
{
cout<<"~Dog 소멸자"<<endl;
}
};
class Cat : public Animal
{
public:
virtual void Speak();
~Cat()
{
cout<<"~Cat 소멸자"<<endl;
}
};
class Pig: public Animal
{
public:
virtual void Speak();
~Pig()
{
cout<<"~Pig 소멸자"<<endl;
}
};
class Duck: public Animal
{
public:
virtual void Speak();
virtual void Walk();
~Duck()
{
cout<<"~Duck 소멸자"<<endl;
}
};
//////////////////////////////////////////// 정의부
//void Animal::Speak(){ cout<<"기본 울음 소리";}
void Animal::Walk(){ cout<<"네발로 걷는다"<<endl;}
////////////////////
void Dog::Speak(){ cout<<"왈 왈 "<<endl;}
///////////////////
void Cat::Speak(){ cout<<"야옹"<<endl;}
//////////////////
void Pig::Speak(){ cout<<"꿀꿀"<<endl;}
//////////////////
void Duck::Speak(){ cout<<"꽥꽥"<<endl;}
void Duck::Walk(){ cout<<"두발로 걷는다"<<endl;}
int main()
{
Animal *ptr; // 객체 포인터
//ptr=new Animal;
int n;
while(1)
{
cout<<"\n1. dog 2.cat 3.pig 4.duck 5.exit\n";
cout<<"choice :";
cin>>n;
switch(n)
{
case 1:
ptr= new Dog;
break;
case 2:
ptr= new Cat;
break;
case 3:
ptr= new Pig;
break;
case 4:
ptr= new Duck;
break;
default:
exit(0);
}
ptr-> Speak();
ptr->Walk();
delete ptr; //동적 객체 해제 => 소멸자 호출
}
return 0;
}
#ifndef _PRODUCT_H_
#define _PRODUCT_H_
#include"date.h"
class Product:public Date
{
public:
Product(char *pN, char *fN, int _price, int _year, int _month, int _day);
~Product();
void OutProduct()const;
Product(const Product &pro) ;
private:
char *p_name;
char *f_name;
int price;
};
#endif
--
//#include"date.h"
#include"product.h"
#include<iostream>
using std::cout;
using std::endl;
Product::Product(char *pN, char *fN, int _price, int _year, int _month, int _day):Date(_year, _month,_day)
{
p_name = new char[strlen(pN)+1];
strcpy(p_name,pN);
f_name = new char[strlen(fN)+1];
strcpy(f_name,fN);
price = _price;
}
Product::~Product()
{
delete []p_name;
delete []f_name;
}
void Product::OutProduct()const
{
cout<<"\t\t******** 상품정보 ******** "<<endl;
cout<<"상품명 : "<<p_name<<endl;
cout<<"제조사 : "<<f_name<<endl;
cout<<"가 격 : "<<price<<endl;
cout<<"제조 년/월/일 : "<<GetYear()<<'/'<<GetMonth()<<'/'<<GetDay()<<'/'<<endl;
}
Product::Product(const Product &pro) : Date(pro.GetYear(), pro.GetMonth(), pro.GetDay())
{// Date(pro)
p_name = new char[strlen(pro.p_name)+1];
strcpy(p_name,pro.p_name);
f_name= new char[strlen(pro.f_name)+1];
strcpy(f_name,pro.f_name);
price= pro.price;
}
--
#ifndef _DATE_H_
#define _DATE_H_
class Date
{
public:
Date(int _year, int _month, int _day);
int GetYear()const;
int GetMonth()const;
int GetDay()const;
private:
int year, month, day;
};
#endif
--
#include"date.h"
Date::Date(int _year, int _month, int _day)
{
year=_year;
month=_month;
day=_day;
}
int Date::GetYear()const
{
return year;
}
int Date::GetMonth()const
{
return month;
}
int Date::GetDay()const
{
return day;
}
--
#include<iostream>
#include"date.h"
#include"product.h"
int main()
{
Product p("새우깡","농심",700,2005,3,4);
Product p1("새우깡","농심",700,2005,3,4);
Product p2 =p1;
p.OutProduct();
p1.OutProduct();
p2.OutProduct();
return 0;
}
#ifndef _PRODUCT_H_
#define _PRODUCT_H_
#include"date.h"
class Product:public Date
{
public:
Product(char *pN, char *fN, int _price, int _year, int _month, int _day);
~Product();
void OutProduct()const;
Product(const Product &pro) ;
private:
char *p_name;
char *f_name;
int price;
};
#endif
--
//#include"date.h"
#include"product.h"
#include<iostream>
using std::cout;
using std::endl;
Product::Product(char *pN, char *fN, int _price, int _year, int _month, int _day):Date(_year, _month,_day)
{
p_name = new char[strlen(pN)+1];
strcpy(p_name,pN);
f_name = new char[strlen(fN)+1];
strcpy(f_name,fN);
price = _price;
}
Product::~Product()
{
delete []p_name;
delete []f_name;
}
void Product::OutProduct()const
{
cout<<"\t\t******** 상품정보 ******** "<<endl;
cout<<"상품명 : "<<p_name<<endl;
cout<<"제조사 : "<<f_name<<endl;
cout<<"가 격 : "<<price<<endl;
cout<<"제조 년/월/일 : "<<GetYear()<<'/'<<GetMonth()<<'/'<<GetDay()<<'/'<<endl;
}
Product::Product(const Product &pro) : Date(pro.GetYear(), pro.GetMonth(), pro.GetDay())
{// Date(pro)
p_name = new char[strlen(pro.p_name)+1];
strcpy(p_name,pro.p_name);
f_name= new char[strlen(pro.f_name)+1];
strcpy(f_name,pro.f_name);
price= pro.price;
}
--
#ifndef _DATE_H_
#define _DATE_H_
class Date
{
public:
Date(int _year, int _month, int _day);
int GetYear()const;
int GetMonth()const;
int GetDay()const;
private:
int year, month, day;
};
#endif
--
#include"date.h"
Date::Date(int _year, int _month, int _day)
{
year=_year;
month=_month;
day=_day;
}
int Date::GetYear()const
{
return year;
}
int Date::GetMonth()const
{
return month;
}
int Date::GetDay()const
{
return day;
}
--
#include<iostream>
#include"date.h"
#include"product.h"
int main()
{
Product p("새우깡","농심",700,2005,3,4);
Product p1("새우깡","농심",700,2005,3,4);
Product p2 =p1;
p.OutProduct();
p1.OutProduct();
p2.OutProduct();
return 0;
}
--------------------------------------------------------------------------------------
human.h
--------------------------------------------------------------------------------------
#ifndef _HUMAN_H_
#define _HUMAN_H_
class Human
{
public:
void SetHuman(char *sN, int _sage);
const char* GetName()const ;
int GetAge() const;
protected:
private:
char name[20];
int age;
};
class Student:public Human
{
public:
void SetStudent(char *pN, int _age, int _id, int _score);
void ShowStudent() const;
private:
int id;
int score;
};
#endif
--------------------------------------------------------------------------------------
human.cpp
--------------------------------------------------------------------------------------
#include<iostream>
#include"human.h"
using std::cout;
using std::endl;
void Student::SetStudent(char *pN, int _age, int _id, int _score)
{
//strcpy(name,pN);
//age=_age;
SetHuman(pN,_age);
id=_id;
score=_score;
}
//상수화된 함수에서는 일반함수의 호출이 불가능
//상수화된 함수만 호출 할 수 있다.
void Student::ShowStudent()const
{
cout<<GetName()<<"\t"<<GetAge()<<"\t"<<id<<"\t"<<score<<endl;
}
void Human::SetHuman(char *sN, int _sage)
{
strcpy(name,sN);
age=_sage;
}
//상수화된 함수에서는 멤버 변수의 주소 리턴이 불가능
//포인터가 가리키는 값을 상수화 시켜서 리턴하면 가능
const char* Human::GetName()const
{
return name;
}
int Human::GetAge()const
{
return age;
};
--------------------------------------------------------------------------------------
main.cpp
--------------------------------------------------------------------------------------
#include <iostream>
#include"human.h"
using std::cout;
using std::endl;
/************************************************
다음과 같은 클래스를 디자인해보자.
1. Human클래스
- protected 멤버변수 : 이름, 나이
2. Student클래스 : Human클래스 상속
- private 멤버변수 : 학번, 점수
- public 멤버함수 : SetStudent - 이름, 나이, 학번, 점수 초기화
ShowStudent - 이름, 나이, 학번, 점수 출력
3. 파일분할하여 프로그램을 작성한다.
************************************************/
int main()
{
Student s1, s2, s3; //객체생성
s1.SetStudent("김수현", 25, 1111, 100); //초기화 함수 호출
s2.SetStudent("장동건", 27, 1112, 90);
s3.SetStudent("김태희", 32, 1113, 50);
s1.ShowStudent(); //출력함수 호출
s2.ShowStudent();
s3.ShowStudent();
return 0;
}
/******** 객체 포인터 *********/
#include<iostream>
using std::cout;
using std::endl;
using std::cin;
class A
{
public:
A(int _a,int _b)
{
a=_a;
b=_b;
}
void show()
{
cout<<"a= "<<a<<", b= "<<b<<endl;
}
private:
int a,b;
};
int main()
{
A *p[5]; // A 타입의 객체를 가리키는 포인터배열 5개
for(int i=0;i<5;i++)
{
int a,b;
cout<<"정수 두개입력 : ";
cin >> a>>b;
p[i] = new A(a,b*10);
}
for(i=0;i<5;i++)
{
p[i]->show();
}
for( i=0;i<5;i++)
{
delete p[i];
// delete []p 는 []<- 이 가리키는 타입이 배열일경우 사용
}
return 0;
}
#include<iostream>
using std::cout;
using std::cin;
using std::endl;
class Telephone
{
public:
Telephone(char *pN, char *pH)
{
strcpy(name,pN);
strcpy(pnum,pH);
}
void showdata()
{
cout<<"이 름: "<<name<<"\t전화번호 : "<<pnum<<endl;
}
private:
char name[20];
char pnum[20];
};
int main()
{
Telephone *T[5];
cout<<" ** 전화번호 입력 **"<<endl;
for(int i=0;i<5;i++)
{
char name[20];
char pnum[20];
cout<<"이름 : ";
cin>>name;
cout<<"전화번호:";
cin>>pnum;
T[i]= new Telephone(name,pnum);
}
for(i=0;i<5;i++)
{
T[i]->showdata();
}
for(i=0;i<5;i++)
{
delete T[i];
}
return 0;
}
#ifndef _STUDENT_H_
#define _STUDENT_H_
class Student
{
public:
//생성자 선언
Student(char *pN, int _age);
void OutStudentInfo() const;
//정적 멤버 함수
static void OutStudentCount();
private:
char pn[20];
int age;
//멤버함수 상수화
const int id;
static int cnt;
};
#endif
------------------------------------------------------------------------
// student.cpp
------------------------------------------------------------------------
#include<iostream>
#include<string.h>
#include"student.h"
using std::cout;
using std::endl;
// 정적 멤버
//1. main 함수가 생성 되기 전에 메모리 할당 된다.
//2.객체 생성과 관계없이 사용할 수 있다.
//3. 클래스 내에 선언 되었지만 클래스 멤버가 아니다.
//4. 정적 멤버 변수의 초기화는 외부에서만 된다.
//5. 정적 멤버 외부 정의시 static 은 선언부에만
//6. 정적 멤버 함수는 정적 멤버 변수만 접근 가능하다.
// (일반 멤버 변수는 접근 불가능 - const 멤버함수가 될 수 없다.)
////////////////////////////////////////////////////
//정적 멤버 초기화.
int Student::cnt=0;
void Student::OutStudentCount()
{
cout<<"전체 학생수는 "<< cnt<<"입니다\n"<<endl;
}
//생성자 정의
Student::Student(char *pN, int _age):id(20041111+cnt)
{
strcpy(pn,pN);
age = _age;
//학번 = 20041111+cnt;
++cnt;
}
void Student::OutStudentInfo() const
{
cout<<"학번 : "<< id<<endl;
cout<<"이름 : "<< pn << endl;
cout<<"나이 : "<< age<<endl;
cout<<"\n\n\n"<<endl;
}
------------------------------------------------------------------------
// main.cpp
------------------------------------------------------------------------
/*
아래의 main함수가 수행될 수 있는 Student클래스를 구현해보자.
- 학생정보는 학번, 이름, 나이로 구성된다.
- 학번은 20041111부터 차례로 1씩 증가 하도록 생성자에서 구현한다.
- 멤버함수
OutStudentCount : 전체 학생수를 출력
OutStudentInfo : 학생정보를 출력
*/
#include <iostream>
#include "student.h"
using std::cout;
using std::cin;
using std::endl;
int main()
{
Student st1("이순신", 25);
Student st2("아무개", 38);
Student::OutStudentCount();
Student st3("홍길동", 29);
Student::OutStudentCount();
st1.OutStudentInfo();
st2.OutStudentInfo();
st3.OutStudentInfo();
return 0;
}
/***************************
this포인터
- 객체선언 시 멤버 변수만 각각 할당되며, 멤버 함수는 공유한다.
때문에 멤버 함수 호출 시 어떤 객체가 멤버 함수를 호출했는지 알 수 있도록
함수의 인자로 객체의 주소를 전달한다.
- 때문에 모든 클래스의 멤버 함수는 객체의 주소를 받을 수 있는 포인터를 인자로
가지고 있어야 하는데 이 포인터 변수를 this포인터라 한다.
- 즉, this포인터는 멤버 함수를 호출한 객체의 주소를 가리키는 포인터다.
***************************/
#include <iostream>
using std::cout;
using std::cin;
using std::endl;
class MyClass
{
public:
void Set(int _i, int _j) //void Set(MyClass *this, int _i, int _j)
{
i = _i;
j = _j;
}
void Out() //void Out(MyClass *this)
{
cout << "i = " << i << ", j = " << j << endl;
}
private:
int i, j;
};
int main()
{
MyClass ob;
ob.Set(1, 10); //Set(&ob, 1, 10)
ob.Out(); //Out(&ob);
return 0;
}
-----------------------------------------------------------------------------------------------------
Date.h
-----------------------------------------------------------------------------------------------------
#ifndef _DATE_H_
#define _DATE_H_
class Date
{
public:
Date(int _y, int _m, int _d);
void OutDate() const;
int GetYear() const;
int GetMonth() const;
int GetDay() const;
private:
int year;
int month;
int day;
};
#endif
-----------------------------------------------------------------------------------------------------
Date.cpp
-----------------------------------------------------------------------------------------------------
#include<iostream>
#include"Date.h"
using std::cout;
using std::endl;
Date::Date(int _y, int _m, int _d):year(_y),month(_m),day(_d)
{
}
void Date::OutDate() const
{
cout<<year<<'/'<<month<<'/'<< day<<endl;
}
int Date::GetYear() const
{
return year;
}
int Date::GetMonth() const
{
return month;
}
int Date::GetDay() const
{
return day;
}
-----------------------------------------------------------------------------------------------------
main.cpp
-----------------------------------------------------------------------------------------------------
#include <iostream>
#include"date.h"
using std::cout;
using std::endl;
using std::cin;
void main()
{
Date d1(2007, 3, 5);
d1.OutDate();
cout << d1.GetYear() << '/' << d1.GetMonth() << '/' << d1.GetDay() << endl;
}