B2024001225 윤지선
2학기 9주차 과제 본문
메인함수 위쪽에 있는 함수는 재활용 가능
#include <iostream>
int main(void)
{
int x;
int y = 10;
char a, b = 'A';
x = y;
std::cout << "x=" << x << " y=" << y << std::endl;
a = b;
std::cout << "a=" << a << " b=" << b << std::endl;
return 0;
}
string copy
문자 배열 대신 string 사용가능
std::string 형으로 사용
문자열을 가지고 놀 때에는 std::string형을 쓴다
#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:
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;
}
출력결과 : 1
객체가 만들어질때마다 그때마다 생성자가 자동으로 호출
Dog() { age = 1; } // 생성자 정의, Dog():age(1){ }, Dog():age{1}{ }
Dog():age(1) {}
Dog() :age{1} {}
이 세가지 방법으로 생성자를 만들 수 있음
생성자가 3가지가 있음
3가지 다 같은 뜻
객체를 만들 때 객체 이르 다음에다가 괄호 열고 객체 초기값을 반드시 써줘야 한다.
#include <iostream>
using std::cout;
class Dog{
private:
int age;
public:
Dog(int a){age=a;cout<<"멍\n";}
~Dog(){cout<<"소멸\n";}
// 소멸자 정의
int getAge();
void setAge(int a);
};
int Dog::getAge()
{
return age;
}
void Dog::setAge(int a)
{
age=a;
}
생성자는 happy가 만들어 질 때 자동으로 만들어짐. 소멸자는 happy가 사라질 때 자동으로 호출됨
# this는 포인터 객체이기 때문에 this는 화살표로 표시
과제
#include <iostream>
#include <string>
class Cat {
private:
std::string name;
int age;
double weight;
public:
Cat();
Cat(std::string value1, int value2, double value3);
~Cat();
std::string getName();
void setName(std::string n);
int getAge();
void setAge(int a);
double getWeight();
void setWeight(double w);
void meow();
};
Cat::Cat() {}
Cat::Cat(std::string value1, int value2, double value3)
: name(value1), age(value2), weight(value3) {}
Cat::~Cat() { std::cout << "소멸\n"; }
std::string Cat::getName() { return this->name; }
void Cat::setName(std::string n) { name = n; }
int Cat::getAge() { return this->age; }
void Cat::setAge(int a) { age = a; }
double Cat::getWeight() { return this->weight; }
void Cat::setWeight(double w) { weight = w; }
void Cat::meow() { std::cout << "야옹\n"; }
int main(void) {
Cat happy("happy", 3, 7.9), kim;
std::cout << "이름 : " << happy.getName() << '\n';
std::cout << "나이 : " << happy.getAge() << '\n';
std::cout << "몸무게 : " << happy.getWeight() << '\n';
}
'2024년 2학기 > C++ 프로그래밍' 카테고리의 다른 글
2학기 10주차 과제 (0) | 2024.11.04 |
---|---|
2학기 10주차 예습과제 (4) | 2024.11.04 |
2학기 9주차 예습과제 (0) | 2024.10.28 |
C++ 시험범위 PPT (0) | 2024.10.19 |
2학기 7주차 과제 (0) | 2024.10.14 |