💻 프로그래밍 언어/C++
C++ 9주차
SA성아
2023. 11. 1. 12:46
객체와 멤버, 생성자/소멸자, this포인터
class
#include <iostream>
using std::cout;
class Dog {
private:
int age;
public:
int getAge();
void setAge(int a);
};
int Dog::getAge()
{
return age;
}
void Dog::setAge(int a)
{
age = a;
}
int main()
{
Dog happy;
happy.setAge(3);
cout << happy.getAge();
return 0;
}
#include <iostream>
using std::cout;
class Dog {
private:
int age;
public:
int getAge();
void setAge(int a);
void cry() {
cout << "멍멍~~\n";
} // 안쪽에 정의
};
int Dog::getAge()
{
return age;
}
void Dog::setAge(int a)
{
age = a;
}
int main()
{
Dog happy;
happy.setAge(3);
cout << happy.getAge();
happy.cry();
return 0;
}
#include <iostream>
using std::cout;
class Dog {
private:
int age;
public:
int getAge();
void setAge(int a);
void cry();
};
int Dog::getAge()
{
return age;
}
void Dog::setAge(int a)
{
age = a;
}
void Dog::cry() //바깥쪽에 정의
{
cout << "멍멍~~\n";
}
int main()
{
Dog happy;
happy.setAge(3);
cout << happy.getAge();
happy.cry();
return 0;
}
#include <iostream>
//using namespace std;
class Dog {
private:
int age;
double weight;
std::string name;
public:
int getAge() {
return age;
}
void setAge(int a) {
age = a;
}
double getWeight() {
return weight;
}
void setWeight(double w) {
weight = w;
}
std::string getName() {
return name;
}
void setName(std::string n) {
name = n;
}
};
int main()
{
Dog happy;
happy.setAge(3);
happy.setWeight(3.5);
happy.setName("해피");
std::cout << happy.getName() << "는 "
<< happy.getAge() << "살, "
<< happy.getWeight() << "kg입니다.\n";
return 0;
}
#include <iostream>
using namespace std;
class Dog {
private:
int age;
double weight;
string name;
public:
int getAge() {
return age;
}
void setAge(int a) {
age = a;
}
double getWeight() {
return weight;
}
void setWeight(double w) {
weight = w;
}
string getName() {
return name;
}
void setName(string n) {
name = n;
}
};
int main()
{
Dog happy;
happy.setAge(3);
happy.setWeight(3.5);
happy.setName("해피");
cout << happy.getName() << "는 "
<< happy.getAge() << "살, "
<< happy.getWeight() << "kg입니다.\n";
return 0;
}
crtl + M, L
ctrl + M, O
문자열 복사
#define _CRT_SECURE_NO_WARNINGS //Visual Studio의 경우
#include <iostream>
#include <string> //or string.h(clang++, gcc 등 주로 온라인 컴파일러)
int main(void)
{
char s1[5];
char s2[5] = "soft"; //원본
//s1 = s2; //error C3863: 배열 형식 'char [5]'은(는) 할당할 수 없습니다.
strcpy(s1, s2); //s2주소의 문자열을 널 문자를 만날 때까지s1주소로 복사
std::cout << "s1=" << s1 << " s2=" << s2 << std::endl;
return 0;
}
파이썬 튜터
문자열 복사: 배열 vs string
#define _CRT_SECURE_NO_WARNINGS
#include <iostream>
#include <string> //or string.h
int main(void)
{
char s1[5];
char s2[5] = "soft";
strcpy(s1, s2); //배열 복사
std::cout << "s1=" << s1
<< " s2=" << s2 << std::endl;
return 0;
}
#define _CRT_SECURE_NO_WARNINGS
#include <iostream>
int main(void)
{
std::string s1;
std::string s2 = "soft";
s1 = s2; //string형 복사는 그냥 대입
//strcpy(s1, s2);
std::cout << "s1=" << s1 << " s2=" << s2;
return 0;
}
문자열 리턴
#include <iostream>
//using namespace std;
char vending(int x)
{
if (x == 1) return 'A';
else return 'B';
}
const char* vending1(int x) //방법1
{
if (x == 1) return "커피";
else return "우유";
}
std::string vending2(int x) //방법2
{
if (x == 1) return "커피";
else return "우유";
}
int main()
{
std::cout << vending(1);
std::cout << vending1(1);
std::cout << vending2(1);
return 0;
}
배열
#define _CRT_SECURE_NO_WARNINGS
#include <iostream>
#include <string> //string.h
using std::cout;
class Cat {
private: //생략가능
int age;
char name[20];
public:
int getAge();
const char* getName();
void setAge(int a);
void setName(const char* pName);
};
int Cat::getAge()
{
return age;
}
void Cat::setAge(int a)
{
age = a;
}
void Cat::setName(const char* pName)
{
strcpy(name, pName); //A
//name=pName; //B, 주소 대입
}
const char* Cat::getName()
{
return name;
}
int main()
{
Cat nabi;
nabi.setName("나비");
nabi.setAge(3); //입력
cout << nabi.getName() << " 나이는"<<nabi.getAge()<<"살이다.";
return 0;
}
string
#define _CRT_SECURE_NO_WARNINGS
#include <iostream>
#include <string> //string.h
using std::cout;
class Cat {
private: //생략가능
int age;
std::string name;
public:
int getAge();
std::string getName();
void setAge(int a);
void setName(std::string pName);
};
int Cat::getAge()
{
return age;
}
void Cat::setAge(int a)
{
age = a;
}
void Cat::setName(std::string pName)
{
//strcpy(name, pName); //A
name=pName; //B, 주소 대입
}
std::string Cat::getName()
{
return name;
}
int main()
{
Cat nabi;
nabi.setName("나비");
nabi.setAge(3); //입력
cout << nabi.getName() << " 나이는"<<nabi.getAge()<<"살이다.";
return 0;
}
객체배열
#include <iostream>
using std::cout;
class Dog {
private:
int age;
public:
int getAge() {
return age;
} //자동 inline함수
void setAge(int a) {
age = a;
} //자동 inline함수
};
int main()
{
int i;
Dog dd[5]; //Dog클래스형 객체배열 dd, 강아지 5마리
for (i = 0; i < 5; i++) {
dd[i].setAge(i);
cout << dd[i].getAge(); //01234
}
return 0;
}
포인터 객체
#include <iostream>
using std::cout;
class Dog {
private:
int age;
public:
int getAge() { return age; }
void setAge(int a) { age = a; }
};
int main()
{
Dog happy, * pd; //일반 객체 happy와 포인터 객체 pd, int x, *px;
pd = &happy; //px=&x; pd가 happy의 주소를 가지고 있음(같은 값)
happy.setAge(5); //일반 객체는 '.'으로 멤버를 접근
cout << happy.getAge() << pd->getAge() <<std::endl; //포인터 객체는 '->'로 멤버를 접근, 5, 5
pd->setAge(2);
cout << happy.getAge() << pd->getAge(); //2, 2
return 0;
}
//매년 기말고사에 나옴
생성자와 소멸자
생성자(Constructor): 객체가 생성될 때 호출되는 특별한 메서드. 객체의 초기화 작업을 담당
소멸자(Destructor): 객체가 소멸될 때 호출되는 메서드. 객체의 정리 작업을 담당
class Example {
public:
// 생성자
Example() {
// 초기화 작업
}
// 소멸자
~Example() {
// 정리 작업
}
};
//C++
class Example {
// 생성자
public Example() {
// 초기화 작업
}
// 소멸자
~Example() {
// 정리 작업
}
}
//C#
class Example {
// 생성자
public Example() {
// 초기화 작업
}
// finalize 메서드
protected void finalize() {
// 정리 작업
}
}
//java
멤버 변수 초기화
#include <iostream>
using std::cout;
class Dog {
private:
int age;
public:
int getAge();
void setAge(int a);
};
int Dog::getAge()
{
return age;
}
void Dog::setAge(int a)
{
age = a;
}
int main()
{
Dog happy,coco;
cout << happy.getAge()<<coco.getAge(); //쓰레기값
return 0;
}
#include <iostream>
using std::cout;
class Dog {
private:
int age;
public:
//Dog() { age = 1; } // 생성자 정의, Dog():age(1){ }, Dog():age{1}{ }
int getAge() { return age; }
void setAge(int a) { age = a; }
};
int main()
{
Dog happy; //happy객체가 생성되는 순간 생성자가 자동 호출됨
cout << happy.getAge();
return 0;
}
실습 4-5: private멤버변수를 특정 값으로 초기화하는 생성자
방법1
#include <iostream>
using std::cout;
class Dog {
private:
int age;
public:
Dog() {
age = 1;
}
//Dog() { age = 1; } // 생성자 정의, Dog():age(1){ }, Dog():age{1}{ }
int getAge() { return age; }
void setAge(int a) { age = a; }
};
int main()
{
Dog happy; //happy객체가 생성되는 순간 생성자가 자동 호출됨
cout << happy.getAge();
return 0;
}
#include <iostream>
using std::cout;
class Dog {
private:
int age;
public:
Dog() {
age = 1;
}
//Dog() { age = 1; } // 생성자 정의, Dog():age(1){ }, Dog():age{1}{ }
int getAge() { return age; }
void setAge(int a) { age = a; }
};
int main()
{
Dog happy, happy1; //happy객체가 생성되는 순간 생성자가 자동 호출됨
cout << happy.getAge() << std::endl; //1
cout << happy1.getAge(); //1
return 0;
}
//기말고사에 생성자 중요
방법2
#include <iostream>
using std::cout;
class Dog {
private:
int age;
public:
Dog() : age(1) { };
//Dog() { age = 1; } // 생성자 정의, Dog():age(1){ }, Dog():age{1}{ }
int getAge() { return age; }
void setAge(int a) { age = a; }
};
int main()
{
Dog happy, happy1; //happy객체가 생성되는 순간 생성자가 자동 호출됨
cout << happy.getAge() << std::endl; //1
cout << happy1.getAge(); //1
return 0;
}
방법3
#include <iostream>
using std::cout;
class Dog {
private:
int age;
public:
//Dog() : age(1) { };
Dog() : age{ 1 } { };
//Dog() { age = 1; } // 생성자 정의, Dog():age(1){ }, Dog():age{1}{ }
int getAge() { return age; }
void setAge(int a) { age = a; }
};
int main()
{
Dog happy, happy1; //happy객체가 생성되는 순간 생성자가 자동 호출됨
cout << happy.getAge() << std::endl; //1
cout << happy1.getAge(); //1
return 0;
}
//기말고사에 많이 나옴
실습 4-5: private멤버변수를 특정 값으로 초기화하는 생성자
#include <iostream>
using std::cout;
class Dog {
private:
int age;
public:
Dog();
int getAge();
void setAge(int a);
};
Dog::Dog() {
age = 1;
}
int Dog::getAge() {
return age;
}
void Dog::setAge(int a) {
age = a;
}
int main()
{
Dog happy; //happy객체가 생성되는 순간 생성자가 자동 호출됨
cout << happy.getAge() << std::endl; //1
return 0;
}
C++에서 변수를 초기화하는 방법
#include <iostream>
int main()
{
int x = 1; //copy initialization,비추
int y(2);//direct initialization, 초기값 지정 방법1
int z{3};//Uniform initialization, C++11, 지정 방법2
int z1{};//Uniform initialization, 자동으로 0,C++11
std::cout << x << y << z << z1;
}
실습 4-6: 생성자의 매개변수로 멤버변수 초기화
#include <iostream>
using std::cout;
class Dog {
private:
int age;
public:
Dog(int a) { age = a; } // 생성자 정의, Dog():age(1){ }, Dog():age{1}{ }
int getAge() { return age; }
void setAge(int a) { age = a; }
};
int main()
{
Dog happy(1), h{2}; //happy객체가 생성되는 순간 생성자가 자동 호출됨
cout << happy.getAge() << h.getAge();
return 0;
}
소멸자
#include <iostream>
using std::cout;
class Dog {
private:
int age;
public:
Dog(int a) { age = a; } // 생성자 정의, Dog():age(1){ }, Dog():age{1}{ }
~Dog() { cout << "소멸\n"; }
int getAge() { return age; }
void setAge(int a) { age = a; }
};
int main()
{
Dog happy(1), h{ 2 }; //happy객체가 생성되는 순간 생성자가 자동 호출됨
cout << happy.getAge() << h.getAge();
return 0;
}
this
#include <iostream>
using std::cout;
class Dog {
private:
int age;
public:
Dog(int age) {
this->age = age;
}
~Dog() { cout << "소멸\n"; }
int getAge() { return age; }
void setAge(int age) {
this->age = age; //현재 클래스에 멤버변수인 age를 가르킬때는 this->를 쓴다
}
};
int main()
{
Dog happy(1), h{ 2 }; //happy객체가 생성되는 순간 생성자가 자동 호출됨
cout << happy.getAge() << h.getAge();
return 0;
}
출처: C++ 프로그래밍 수업 ppt