본문 바로가기

C++ 프로그래밍 (1학년 2학기)

231102 C++프로그래밍 9주차

1.

 

2.

직접참조연산자(.) : 일반 객체가 멤버(변수/함수)에 접근하기 위해 사용

간접참조연산자(->) : 포인터 객체가 멤버(변수/함수)에 접근하기 위해 사용

ex)

happy.getAge() // 해피의 나이를 얻는다.

happy.bark() // 해피가 짖는다.

pHappy->getAge() // pHappy의 나이를 얻는다.

pHappy->bark() // 포인터 객체 pHappy가 짖는다.

 

3. 

#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;
}

 

4.

함수명 기능 의미
strcpy(st1,st2) 문자열 st2를 st1으로 복사 Copy a string. 
strcat(st1,st2) 문자열 st2를 st1과 연결 Append a string. (concatenation) 
strcmp(st1,st2) 문자열 st1과 st2를 비교 Compare strings.
strlen(st)  문자열 st의 길이  Get the length of a string. 

 

5. 

#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;
}

6. 문자열 복사 : 배열 vs string

7. 문자열을 리턴할 때에는 const char*을 써줘야 한다.

#include <iostream>
using namespace std;
const char* vending(int x) // std::string도 가능
{
	if (x == 1) return "커피";
	else return "유자차";
}
int main()
{
	cout << vending(1);
	return 0;
}

8.  

#define _CRT_SECURE_NO_WARNINGS
#include <iostream>
#include <string> //string.h
using namespace std;
class Cat {
private: //생략가능
	int age;
	char name[20]; // A
	//const char *name; //B, 비추
    //string name; //C
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) { //void Cat::setName(string pName)
	strcpy(name, pName); //A
	//name=pName; //B, 주소 대입
}
const char* Cat::getName() { //string Cat::getName()
	return name;
}
int main()
{
	Cat nabi;
	nabi.setName("나비");
	nabi.setAge(3); //입력
	cout << nabi.getName() << " 나이는" << nabi.getAge() << "살이다.";
		return 0;
}

9. 포인터 객체

#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;
	happy.setAge(5); //일반 객체는 '.'으로 멤버를 접근
	cout << happy.getAge() << pd->getAge(); //포인터 객체는 '->'로 멤버를 접근
	pd->setAge(2); //pd는 포인터변수라서 '.'으로 쳐도 컴파일러에서 자동으로 '->'로 바꿔줌
	cout << happy.getAge() << pd->getAge();
	return 0;
}

10. 생성자와 소멸자

C++과 C#은 모두 객체지향 프로그래밍 언어로서, 생성자와 소멸자는 객체의 생성과 소멸 시에 호출되는 특별한 메서드이다.

C++에서의 생성자와 소멸자 예

#include <iostream>

class MyClass {
public:
    // 생성자
    MyClass() {
        std::cout << "객체가 생성되었습니다." << std::endl;
    }

    // 소멸자
    ~MyClass() {
        std::cout << "객체가 소멸되었습니다." << std::endl;
    }
};

int main() {
    MyClass obj; // MyClass의 객체 생성

    // 프로그램 종료 시 객체가 자동으로 소멸됨
    return 0;
}

C#에서의 생성자와 소멸자 예

using System;

class MyClass {
    // 생성자
    public MyClass() {
        Console.WriteLine("객체가 생성되었습니다.");
    }

    // 소멸자
    ~MyClass() {
        Console.WriteLine("객체가 소멸되었습니다.");
    }
}

class Program {
    static void Main(string[] args) {
        MyClass obj = new MyClass(); // MyClass의 객체 생성

        // 프로그램 종료 시 객체가 자동으로 소멸됨
    }
}

11. private멤버변수를 특정 값으로 초기화하는 생성자

#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;
}
------------------------------------------------
#include <iostream>
using std::cout;
class Dog {
private:
	int age;
public:
	Dog(); // 생성자 선언
	int getAge();
	void setAge(int a);
};
Dog::Dog() // 생성자 정의, 리턴형을 쓰면 안됨
{
	age = 1; // private멤버변수 Age를 초기화
}
int Dog::getAge()
{
	return age;
}
void Dog::setAge(int a)
{
	age = a;
}
int main()
{
	Dog happy; //happy객체가 생성되는 순간 생성자가 자동 호출됨
	cout << happy.getAge();
	return 0;
}

12. C++에서 변수를 초기화하는 방법

#include <iostream>
int main()
{
	int x = 1; //copy initialization,비추
	int y(2);//direct initialization
	int z{ 3 };//Uniform initialization, C++11
	int z1{};//Uniform initialization, 자동으로 0,C++11
	std::cout << x << y << z << z1;
}

13. 생성자에 매개변수가 있으면 객체 이름 다음에 괄호안에 매개변수로 넘어갈 값을 써야 한다.

14. 소멸자는 객체가 사라질 때 소멸된다. [ ~Dog(){cout<<"소멸\n";} ]

15. this 포인터변수 (다른 언어에서는 self)

#include <iostream>
using std::cout;
class Dog {
private:
	int age;
public:
	Dog(int a) { age = a;}
	~Dog() { cout << "소멸\n"; }
	// 소멸자 정의
	int getAge() { return age; }
	void setAge(int age) {
		this->age = age;
	}
};
int main()
{
	Dog happy(1), h(2);
	cout << happy.getAge() << h.getAge();
	happy.setAge(5); cout << happy.getAge();
	return 0;
}
댓글