+)cmd+shift+5

 

 

https://bbiguduk.gitbook.io/swift

swift에서는 초깃값이 있을 경우에는 컴파일러가 타입 추론(type inference)을 하므로 데이터 타입을 명시할 필요 없음 (var myNumber = 10 )

 

swift자료형

//int x = 10
var x = 10
print(type(of: x))
//x = 10
print(x)

강의자료 p11

//int x = 10
var x = 10
print(type(of: x))
//x = 10
print(x)
let s = MemoryLayout.size(ofValue:x)//8
print(s)

다양한 프로그래밍 언어의 ' '와 " "의 용도

-문자 데이터 타입: character

character형은 일반적으로 자료형을 생략하지 않음

 

다양한 프로그래밍 언어의 string interpolation하는 방법

  • Python: f 문자열 앞에 붙여 {} 안에 변수를 넣습니다.
  • JavaScript: 백틱(```)을 사용하여 ${} 안에 변수를 넣습니다.
  • Java: 문자열 연결을 통해 변수를 추가합니다.
  • C#: $를 사용하여 {} 안에 변수를 넣습니다.
  • Ruby: #{}를 사용하여 변수를 문자열 안에 포함합니다.
  • Swift: \()를 사용하여 변수를 문자열 안에 포함합니다.
  • PHP: 문자열 안에 $로 변수를 직접 포함합니다.
  • Kotlin: $를 사용하여 변수를 문자열 안에 포함합니다.
//int x = 10
var x = 10

//x = 10

print("age=\(x)")//age=10

 

 

 

출처: iOS프로그래밍 기초 수업/ 한성현 교수님

'Swift' 카테고리의 다른 글

iOS 프로그래밍 기초 7주차  (0) 2024.10.16
iOS 프로그래밍 기초 6주  (0) 2024.10.15
iOS프로그래밍 기초 5주차  (0) 2024.10.03
iOS프로그래밍 4주차  (0) 2024.09.25
<1주차>iOS 프로그래밍 기초  (2) 2024.09.04

클라우드 컴퓨팅

-인터넷을 통해 여러 컴퓨터 자원(서버, 저장공간, 프로그램 등)을 나눠서 사용할 수 있게 해주는 방법

-필요한 만큼 빠르게 자원을 받을 수 있어서, 복잡한 절차 없이 편리하게 사용할 수 있음

-클라우드 컴퓨팅 ≒ 은행 예금

    ->은행에 돈을 예금해 두면 언제든지 필요할 때 찾아 쓸 수 있듯이, 클라우드 컴퓨팅도 필요한 파일이나 프로그램을 클           라우드에 저장해 두면, 언제 어디서나 인터넷만 있으면 꺼내 쓸 수 있음

 

특징

-주문형 셀프 서비스: 사용자가 필요할 때 자원 요청, 관리 가능

-광범위한 네트워크 접속: 인터넷이 연결된 모든 장치에서 클라우드 서비스에 접근 가능

-리소스의 공유: 여러 사용자가 동일한 자원을 공유해 효율성을 높이고 비용을 절감

-신속한 확장형: 수요에 따라 자원을 쉽게 추가하거나 줄일 수 있음

-측정 가능한 서비스: 사용자가 소비한 자원을 정량적으로 측정해 요금이 청구됨

 

 

정보처리 시스템 발전 과정

-메인 프레임(1970~80년대)

: 대형 컴퓨터, 중앙에서 모든 데이터를 처리하고 여러 사용자들이 터미널을 통해 접속하여 작업하는 방식,

클라이언트 단말기는 특별한 기능 없이 입출력 기능 수행

 

-클라이언트 서버(1990년대)

: 사용자의 컴퓨터(클라이언트)와 서버가 연결되어 데이터를 요청하고 받는 구조,여러 사용자가 동시에 서비스를 이용할 수 있게 해줌 /집중처리 방식(서버 중심)-> 분산 처리 방식(단말 중심)

 

-웹 기반의 네트워크 컴퓨팅(2000년대)

: 인터넷을 통해 소프트웨어와 데이터를 제공받는 방식, 사용자는 브라우저를 통해 언제 어디서나 서비스에 접근할 수 있음

/분산환경-> 서버 중심 중앙 컴퓨팅 환경

 

클라우드 서비스 모델

-IaaS(Infrastructure as a Service)

-CPU와 하드웨어를 네트워크를 통해 서비스로 제공

-대표서비스: 가상서버, 온라인 스토리지

-하드웨어 자원을 소프트웨어적으로 나누어 자유롭게 확장, 축소 가능

-ex) Amazon Elastic Compute Cloud(EC2): 사용자가 클라우드에서 갓강 서버를 쉽게 생성하고 관리할 수 있도록 해주는 서비스

 

-PaaS(Platform as a Service)

-개발자들이 애플리케이션을 개발, 테스트, 배포할 수 있는 플렛폼을 제공

-서버 및 미들웨어의 상세 설정은 불가능

-컨테이너화된 애플리케이션을 자동으로 배포하고, 관리하며, 확장하는 오픈소스 플랫폼

 

-SaaS(Software as a Service)

- 사용자가 인터넷을 통해 소프트웨어를 직접 사용하고 관리할 필요 없이 클라우드에서 제공

- 멀티 테넌트 방식: 하나의 서버를 여러 기업에서 공유

-다양한 기기로 접속 가능

-ex) google workspace

 

온프레미스(on_premise)

-회사 내에 자체적으로 데이터 센터를 보유하고 시스템 구축에서 운용까지 직접 수행하는 상태

 

온프레미스 VS 클라우드

 

1.경제성

-클라우드: 초기비용 낮음, 운영 비용 유연

-온프레미스: 초기 하드웨어 및 소프트웨어 구매에 높은 비용 필요, 유지보수 비용도 지속적으로 발생

 

2. 유연성

-클라우드: 필요에 따라 자원을 쉽게 확장, 축소 가능, 변화하는 요구에 빠르게 대응 가능함

-온프레미스: 자원 확장 어렵고, 유연성이 제한적

 

3.가용성

-클라우드: 여러 지역에 분산된 데이터 센터를 활용하여 높은 가용성을 제공하며, 서비스 중단 시 빠른 복구가 가능

-온프레미스: 가용성을 높이기 위해 추가적인 장비와 이중화 시스템이 필요하지만 초기 투자와 관리가 복잡

4.빠른 구축 속도

-클라우드: 몇 분 내로 인프라를 설정하고 배포 할 수 있어, 빠른 시작 가능

-온프레미스: 하드웨어 설치와 설정에 시간이 걸리며, 구축 속도가 느림

 

퍼블릭 클라우드(Public Cloud)

: 인터넷을 통해 불특정 다수에게 서비스 제공, 클라우드 사업자가 시스템 구축, 데이터 센터를 보유하지 않아 초기 투자 부담 적음

 

프라이빗 클라우드 (Private Cloud)

  • 전용 데이터센터: 클라우드 서비스 제공자가 기업 전용의 데이터센터 환경을 구축합니다.
  • 보안 및 맞춤화: 보안이 용이하며, 독자적인 기능이나 서비스 추가가 쉽습니다.
  • 주요 사용처: 공공기관 및 금융기관에서 많이 사용됩니다.

유형

  1. 온프레미스 프라이빗 클라우드: 자사 전용 클라우드 환경을 구축하고 운영하며, 강력한 자체 보안 정책을 적용합니다.
  2. 호스티드 프라이빗 클라우드: 클라우드 사업자가 사용자별로 클라우드 환경을 제공하며, 단기간에 전용 환경을 구축할 수 있습니다. 월 비용을 지불하고 전용선이나 VPN을 통해 높은 보안 환경을 제공합니다.

 

기타 

커뮤니티클라우드(Community Cloud)

• 비슷한목적을가진기업들끼리클라우드시스템을형성해데이터센터를공동운영

하이브리드클라우드(Hybrid Cloud)

• 클라우드서비스들과온프레미스시스템을연계시켜활용

 

비용 비교

  • 온프레미스 시스템:
    • 초기 도입 비용: 하드웨어 및 소프트웨어 조달비용.
    • 운영 비용: 시설 관리비, 하드웨어 리스비, 임대비, 유지보수비, 회선비, 인건비.
  • 클라우드:
    • 유연한 서버 자원 사용으로 비용 최적화.
    • 클라우드 사업자가 운영해 인건비 최소화.
    • 단, 장기간 이용 시 또는 대규모 시스템 구축/운용 시 온프레미스가 저렴할 수 있습니다.

클라우드 서비스의 책임 분계선

  • 책임 분담 명확화: 클라우드 사업자와 이용자 간의 책임을 명확히 확인해야 합니다.
  • 사용자 환경의 손해: 사용자의 환경에서 발생한 손해는 클라우드 사업자가 부담하지 않음을 규정합니다.
  • 접속 환경 장애: 이용자의 접속 환경 문제에 대해 클라우드 사업자는 책임을 지지 않습니다.
  • 이용 모델에 따른 차이: 클라우드 서비스 이용 모델에 따라 책임 분계선이 달라집니다.
  • 보험 상품 가입 검토: 장애 발생 시 손실 및 손해배상 비용을 보장하는 보험 상품 가입을 고려해야 합니다.
  • 보안 사고 대응: 사고 발생 시 클라우드 사업자가 정보를 어떻게 제공하는지와 지원 체계 확인이 필요합니다.
  • 커뮤니케이션 체계 구축: 클라우드 사업자와 원활한 커뮤니케이션 체계를 마련해야 하며, 24시간 365일 지원 가능 여부가 중요합니다.

 

 

 

출처: 공준익 교수님 자료 참고

'네트워크 보안' 카테고리의 다른 글

데이터베이스 서비스  (0) 2024.12.15
클라우드 기타 용어 간단 정리  (0) 2024.11.25
클라우드를 실현하는 기술  (0) 2024.11.25
클라우드 서비스  (0) 2024.11.25

 

swift를 이용한 코드

Python

for _ in range(10):
    print("김다현")

 

 

JavaScript

for (let i = 0; i < 10; i++) {
    console.log("김다현");
}

Java

public class Main {
    public static void main(String[] args) {
        for (int i = 0; i < 10; i++) {
            System.out.println("김다현");
        }
    }
}

C

#include <stdio.h>

int main() {
    for (int i = 0; i < 10; i++) {
        printf("김다현\n");
    }
    return 0;
}

C++

#include <iostream>

int main() {
    for (int i = 0; i < 10; i++) {
        std::cout << "김다현" << std::endl;
    }
    return 0;
}

Ruby

10.times do
    puts "김다현"
end

 PHP

<?php
for ($i = 0; $i < 10; $i++) {
    echo "김다현\n";
}
?>

Swift

for _ in 1...10 {
    print("김다현")
}

Go

package main

import "fmt"

func main() {
    for i := 0; i < 10; i++ {
        fmt.Println("김다현")
    }
}

Kotlin

fun main() {
    repeat(10) {
        println("김다현")
    }
}

 

 

 

출처: iOS프로그래밍 기초 -한성현 교수님

'Swift' 카테고리의 다른 글

iOS 프로그래밍 기초 7주차  (0) 2024.10.16
iOS 프로그래밍 기초 6주  (0) 2024.10.15
iOS프로그래밍 기초 5주차  (0) 2024.10.03
iOS프로그래밍 4주차  (0) 2024.09.25
iOS프로그래밍 기초 2주차  (0) 2024.09.11

//18
#include <iostream>
using namespace std;
int main() {
	cout << "디폴트\n";
	cout.width(10); //그 다음 cout 출력폭을 결정함
	cout << -50 << endl;
	cout << "[ * fill ]\n";
	cout.fill('*');//밑에 나오는  빈칸이 있으면 그 문자로 채워라(문자만 가능 ''/ 큰따옴표(문자열) 불가)
	cout.width(10);
	cout << -50 << endl;
	cout.width(10);
	cout << 100.25 << endl;
	cout.width(10);
	cout << "HanSH" << endl;
	cout.fill(' ');
	cout.precision(6); //소수점을 제외한 전체 자리수
	cout << 12.34567 << endl;
	cout << fixed; //소수점 이하의 자리수만 다루게 함
	cout.precision(3);
	cout << 12.34567 << endl;
	return 0;
}
//22
#include <iostream>
using namespace std;
int main()
{
	int num = 100;
	cout << "10진수: " << num << endl;
	cout << "16진수: " << hex << num << endl;
	cout << "8진수: " << oct << num << endl;
	return 0;
}
//23

#include <iostream>
#include <iomanip>
using namespace std;
int main() {
	cout << "abcdefg\n";
		cout << 12345 << endl;
	cout << 123.45 << endl;
	cout << "10칸\n";
		cout << setfill('*');//매개변수를 갖는 조절자 사용시#include <iomanip>필요,*로 채우기 문자를 설정한다
	cout << setw(10) << "abcdefg" << endl; //매개변수를 갖는 조절자 사용시#include <iomanip>필요
	cout << setw(10) << 12345 << endl;//매개변수를 갖는 조절자 사용시#include <iomanip>필요
	cout << setw(10) << 123.45 << endl;//매개변수를 갖는 조절자 사용시 #include <iomanip>필요,setwn으로 필드 폭을 설정한다
	return 0;
}

 

 

파일을 열고 다 가지고 놀면 닫고..? 파일을 개방하는 2가지 방법!

<출력을 파일에 하는 방법>

#include <iostream>
#include <fstream>
using namespace std;
int main()
{
	ofstream xxx("test2.txt"); // ofstream파일 만들기 출력파일 스트림 객체 hout 선언(hout말고 다른거 써도 됨)
	
	xxx << "kdhhhh\n";
	xxx << 12 << endl << 100 << endl;
	xxx.close(); //파일 종결
	return 0;
}
#include <iostream>
#include <fstream>
using namespace std;
int main()
{//abc.txt파일에 자신의 이름 저장하기
	ofstream xxx("abc.txt"); // 출력파일 스트림 객체 hout 선언
	
	xxx << "kdh\n";
	xxx.close(); //파일 종결
	return 0;
}
#include <iostream>
#include <fstream>
using namespace std;
int main()
{//만들어 놓았던 데이터를 불러올때 사용하는 방법(hin만는거)
	ifstream hin("test.txt"); // 입력파일 스트림 객체 hin 선언
	if (!hin) {
		cout << "입력할 파일을 열 수 없습니다.";
		return 1;
	}
	char str[50];
	int i, j;
	hin >> str >> i >> j;
	cout << str << " " << i << " " << j << endl;
	hin.close(); // 파일 종결
	return 0;
}
#include <iostream>
#include <fstream>
using namespace std;
int main()
{
	ofstream hout("test.txt");//파일입출력을 할때는ofstream으로 저장
	if (!hout) {
		cout << "출력할 파일을 열 수 없음.";
		return 1;
	}
	hout << "HanSH\n";
	hout.close();
	ifstream hin("test.txt");//파일을 불러올때는ifstream으로 불러옴
	if (!hin) {
		cout << "입력할 파일을 열 수 없음.";
		return 1;
	}
	char str[50];
	hin >> str;
	cout << str << endl;
	hin.close();
	return 0;
}
#include <iostream>
#include <fstream>
using namespace std;
int main()
{//출력ofstream 입력ifstream
	char ch;
	ifstream hin("test.txt");
	if (!hin) {
		cout << "입력할 화일을 열 수 없음";
		return 1;
	}
	hin.unsetf(ios::skipws);//공백 무시x
	while (!hin.eof()) {
		hin >> ch;
		if (ch == ' ') ch = '*';
		cout << ch;
	}
	hin.close();
	return 0;
}

#include <iostream>
using std::cout;
using std::endl;
int main(void)
{
	int x = 10;
	int& rx = x;//rx는 x의 참조자
	cout << x << " " << rx << endl;
	rx = rx + 10;
	cout << x << " " << rx << endl; //참조자(rx)에 변화를 주면 그 타켓(x)도 변함
	x = x + 10;
	cout << x << " " << rx << endl; //타켓(x)에 변화를 주면 그 참조자(rx)도 변함
	return 0;
}

출처: 1학년 2학기 수업자료/ 한성현 교수

 

'C++프로그래밍' 카테고리의 다른 글

C++프로그래밍 13주차 과제  (1) 2023.11.29
C++프로그래밍 12주차 과제  (1) 2023.11.22
C++프로그래밍 11주차 과제  (0) 2023.11.15
c++프로그래밍 10주차 과제  (1) 2023.11.08
C++ 프로그래밍 9주차 과제  (0) 2023.11.01

 <private와 protected 접근 속성의 공통점과 차이점>

  • 공통점: 두 접근 제어자 모두 클래스의 외부에서 직접 접근이 불가능, 즉 객체를 통해 멤버 변수에 직접 접근하거나 멤                버 변수를 호출하는 것이 불가능

 

  • 차이점: 1. private멤버는 해당 클래스의 객체에서만 접근 가능, 즉 동일한 클래스의 다른 객체 똔느 상속받은 자식 클                      래스 에서도 접근 불가능

 

                      2.protected멤버는 해당 클래스와 동일한 클래스의 다른 객체, 그리고 상속받은 자식 클래스에서 접근이 가                             능, 하지만 자식 클래스의 객체를 통해서는 접근이 불가능

 

자식쪽에서 부모쪽으로 매개변수를 넘기는 방법 /부모 생성자가 먼저 생성이 되는데 자식쪽에서 부모쪽으로 매개변수를 넘기는 방법이다

 

  • 파이썬 다중 상속 예시
# 부모 클래스 1
class Parent1:
    def __init__(self):
        self.parent1 = "부모 클래스1"

    def print_parent1(self):
        print(self.parent1)

# 부모 클래스 2
class Parent2:
    def __init__(self):
        self.parent2 = "부모 클래스2"

    def print_parent2(self):
        print(self.parent2)

# 다중 상속을 받는 자식 클래스
class Child(Parent1, Parent2):
    def __init__(self):
        Parent1.__init__(self)  # 부모 클래스1의 생성자 호출
        Parent2.__init__(self)  # 부모 클래스2의 생성자 호출
        self.child = "자식 클래스"

    def print_child(self):
        print(self.child)

if __name__ == "__main__":
    child = Child()
    child.print_parent1()  # 부모 클래스1의 메소드 호출
    child.print_parent2()  # 부모
  • 2개의 기본 클래스 상속1
#include <iostream>
using std::cout;
using std::endl;
class A1 // 아버지
{
	int a;
public:
	A1(int i) { a = i; }
	int getA() { return a; }
};
class A2 // 어머니
{
	int b;
public:
	A2(int i) { b = i; }
	int getB() { return b; }
};
class B :public A1, public A2
{
	// 기본 클래스 A1과 A2로부터
	// 상속 받은 파생 클래스
	int c;
public:
	B(int i, int j, int k) :A1(i), A2(j) { c = k; }
	// i는 기본클래스 A1의 생성자로,
	// j는 기본클래스 A2의 생성자로
	// 각각 매개변수 전달, { c = k; }초기화 하는것
	void show() {
		cout << getA() << ' ' << getB() << ' ' << c << endl;
	}
};
int main()
{
	B bb(1, 2, 3);
	bb.show();
	return 0;
}
  • 여러 개의 기본 클래스를 상속 받을 때, 생성자와 소멸자의실행 순서
#include <iostream>
using std::cout;
class A1 // 기본 클래스 1
{
	int a;
public:
	A1() { cout << "A1의 생성자.\n"; }
	~A1() { cout << "A1의 소멸자.\n"; }
};
class A2 // 기본 클래스 2
{
	int b;
public:
	A2() { cout << "A2의 생성자.\n"; }
	~A2() { cout << "A2의 소멸자.\n"; }
};
class B : public A1, public A2
	// 기본 클래스 1과 2로부터
	// 상속 받은 파생 클래스 
{
	int c;
public:
	B() { cout << "B의 생성자.\n"; }
	~B() { cout << "B의 소멸자.\n"; }//부모에 쓰는 생성자는 먼저 쓰는 순서대로/ 소멸자는 역순으로 호출한다
};
int main()
{
	B bb;
	return 0;
}

클래스 다이어그램: 위에는 부모 아래는 자식, 자식에서 부모로 화살표(색x)

 

  • 부모 클래스 완성( 사람클래스(Man,멤버변수:이름,나이)를 만드시오.)
#include<iostream>
//using namespace std;
using std::cout;
using std::endl;
using std::string;
class Man {
	string name;
	int age;
public:
	Man(std::string n, int a) {
		name = n;//초기화
		age = a;
	}
	void m_show() {
		cout << "이름:" << name << endl;
		cout << "나이:" << age << endl;
	}
};

 

  • 사람클래스로부터 상속받은 학생클래스(Student)를 만드시오. (멤버변수:반,학번), 생성자, 기타함수
#include<iostream>
//using namespace std;
using std::cout;
using std::endl;
using std::string;
class Man {
	string name;
	int age;
public:
	Man(string name, int age) {
		this->name = name;//초기화
		this->age = age;
}
	//Man(string n, int a) {
	//	name = n;//초기화
	//	age = a;
	//}
	
	void m_show() {
		cout << "이름:" << name << endl;
		cout << "나이:" << age << endl;
	}
};

class Student : public Man{
	string ban;
	string hak;
	Student(string n, int a, string b, string h) :Man(n,a) {

		ban = b;
		hak = h;
	}
	void s_show() {
		m_show();
		cout << "반:" << ban << endl;
		cout << "학번:" << hak << endl;

	}
};

 

  • 사람클래스로부터 상속받은 교수(Teacher)클래스를 만드시오. (멤버변수:전공,담당과목), 생성자, 기타함수
#include<iostream>
//using namespace std;
using std::cout;
using std::endl;
using std::string;
class Man {
	string name;
	int age;
public:
	Man(string name, int age) {
		this->name = name;//초기화
		this->age = age;
}
	//Man(string n, int a) {
	//	name = n;//초기화
	//	age = a;
	//}
	
	void m_show() {
		cout << "이름:" << name << endl;
		cout << "나이:" << age << endl;
	}
};

class Student : public Man{
	string ban;
	string hak;
	Student(string n, int a, string b, string h) :Man(n,a) {

		ban = b;
		hak = h;
	}
	void s_show() {
		m_show();
		cout << "반:" << ban << endl;
		cout << "학번:" << hak << endl;

	}
};

class Teacher : public Man {
	string major;
	string subject;
	Teacher(string n, int a, string m, string s) :Man(n, a) {

		major = m;
		subject = s;
	}
	void t_show() {
		m_show();
		cout << "전공:" << major << endl;
		cout << "담당과목:" << subject << endl;

	}
};

완성

#include<iostream>
//using namespace std;
using std::cout;
using std::endl;
using std::string;
class Man {
protected:
	string name;
	int age;
public:
	Man(string name, int age) {
		this->name = name;//초기화
		this->age = age;
}
	//Man(string n, int a) {
	//	name = n;//초기화
	//	age = a;
	//}
	
	void m_show() {
		cout << "이름:" << name << endl;
		cout << "나이:" << age << endl;
	}
};

class Student : public Man{
	string ban;
	string hak;
public:
	Student(string n, int a, string b, string h) :Man(n,a) {

		ban = b;
		hak = h;

	}
	void s_show() {
		m_show();
		cout << "반:" << ban << endl;
		cout << "학번:" << hak << endl;

	}
};

class Teacher : public Man {
	string major;
	string subject;
public:
	Teacher(string n, int a, string m, string s) :Man(n, a) {

		major = m;
		subject = s;
	}
	void t_show() {
		m_show();
		cout << "전공:" << major << endl;
		cout << "담당과목:" << subject << endl;

	}
};





int main()
{
	Student kks("김컴소", 20, "C반", "202012000");
	Teacher hsh("한미소", 40, "전산", "C++프로그래밍");
	kks.s_show();
	hsh.t_show();
	return 0;
}

 

#include <iostream>
using std::cout;
class Dot {//부모클래스
public:
	virtual void draw() {cout << "Dot::draw()\n";}//virtual꼭 필요
	void print() {
	cout << "Dot 클래스\n";
	draw();//draw함수 호출
		}
	};
	class Line :public Dot { //자식클래스
	public:
		void draw() {//void draw() override ,override는 써도 안써도 상관없음
			cout <<"Line::draw()\n";}
		};
		int main() {
			Line line;
			line.print();
			return 0;
		}

출처: 1학년 2학기 수업자료/ 한성현 교수님

'C++프로그래밍' 카테고리의 다른 글

c++프로그래밍 15주차 과제  (0) 2023.12.13
C++프로그래밍 12주차 과제  (1) 2023.11.22
C++프로그래밍 11주차 과제  (0) 2023.11.15
c++프로그래밍 10주차 과제  (1) 2023.11.08
C++ 프로그래밍 9주차 과제  (0) 2023.11.01

<상속 문법 예제>

1.python

# 부모 클래스
class Animal:
    def eat(self):
        print("Eating...")

# 자식 클래스
class Cat(Animal):
    def meow(self):
        print("Meow!")

cat = Cat()
cat.eat()  # "Eating..." 출력
cat.meow()  # "Meow!" 출력

2.java

// 부모 클래스
public class Animal {
    public void eat() {
        System.out.println("Eating...");
    }
}

// 자식 클래스
public class Cat extends Animal {
    public void meow() {
        System.out.println("Meow!");
    }
}

// 메인 클래스
public class Main {
    public static void main(String[] args) {
        Cat cat = new Cat();
        cat.eat();  // "Eating..." 출력
        cat.meow();  // "Meow!" 출력
    }
}

3.javascript

// 부모 클래스
class Animal {
    eat() {
        console.log("Eating...");
    }
}

// 자식 클래스
class Cat extends Animal {
    meow() {
        console.log("Meow!");
    }
}

const cat = new Cat();
cat.eat();  // "Eating..." 출력
cat.meow();  // "Meow!" 출력

 

   - 상속은 부모 자식간의 관계 : 멋있게(?) 말할때는 is a관계라고 한다

private를 제외하고 모두 물려 받는다

 

부모의 protected와 public이 그대로 자식에게 돌아온다

 #include <iostream>
using std::cout;
using std::endl;
class A // 기본 클래스 
{
	int x;//생략가능
public:
	void setX (int i) {x =i;}
	void showX() { cout << x << endl; }
};
class B:public A //파생 클래스
{
	//아무 것도 없어요. 그러나!
};
int main() {
	A aa;
	aa.setX(1);
	aa.showX(); B bb;
	bb.setX(10);
	bb.showX();
	return 0;
}
#include <iostream>
using std::cout;
using std::endl;

class A // 기본 클래스 A 선언
{
int x; // private 멤버 변수 x
public:
void setX(int i) { x = i; } // x에 값을 설정하는 public 멤버 함수
void showX() { cout << x << endl; } // x의 값을 출력하는 public 멤버 함수
};

class B :public A // A 클래스를 상속받는 파생 클래스 B 선언
{
int y; // private 멤버 변수 y
public:
void setY(int i) { y = i; } // y에 값을 설정하는 public 멤버 함수
void showY() { cout << y << endl; } // y의 값을 출력하는 public 멤버 함수
};

int main()
{
B bb; // B 클래스의 객체 bb 생성
bb.setX(1); // bb 객체의 x값을 1로 설정 (A 클래스의 메서드 이용)
bb.setY(2); // bb 객체의 y값을 2로 설정 (B 클래스의 메서드 이용)
bb.showX(); // bb 객체의 x값 출력 (A 클래스의 메서드 이용)
bb.showY(); // bb 객체의 y값 출력 (B 클래스의 메서드 이용)
return 0;
}

 

#include <iostream>
using std::cout;
using std::endl;
class A
{
	int x;//private 생략 가능 
public:
	void setX(int i) { x = i; }
	void showX() { cout << x << endl; }
};
class B :public A
{
	int y;  
public:
	void setY(int i) { y = i; }
	void
		showXY() { showX();  cout << y << endl; }
};
int main()
{
	B bb;
	bb.setX(1); // 기본클래스의 멤버접근
	bb.setY(2); // 파생클래스의 멤버접근
	bb.showX(); // 기본클래스의 멤버접근
	bb.showXY(); // 파생클래스의 멤버접근
	return 0;
}

In-class member initializers:클래스 안에서 멤버 변수를 바로 초기화하는 방법

#include <iostream>
using std::cout;
using std::endl;
class A
{
	int x = 1;
public:
	A() { x = 2; } //(=A():x(2){})

	void setX(int i) { x = i; }
	int getX() { return x; }
};
int main()
{
	A a1; //디폴트 생성자는 사라짐
	cout << a1.getX() << endl;
	return 0;
}
#include <iostream>
using std::cout;
using std::endl;
class A
{
	int x;
public:
	void setX(int i) { x = i; }
	void showX() { cout << x << endl; }
};
class B :private A //비공개적으로 상속받는다/ 자식만 사용가능, 그래서 setX와 ShowX를 사용
{
	int y;
public:
	void setXY(int i, int j) { setX(i); y = j; }
	// 기본 클래스의 public 멤버 접근
	void showXY() { showX(); cout << y << endl; }
};
int main()
{
	B bb;
	bb.setXY(1, 2); // 파생클래스의 멤버접근
	bb.showXY(); // 파생클래스의 멤버접근
	return 0;
}

protected부분이 없으면 private부분으로 상속된다

protected, private공통점 외부에서 둘다 접근 불가

차이점: protected는 자식에게 상속가능, private는 자식에게 상속 불가

-부모에서는 항상 private를 썼는데 자식에게 물려줄려면 protected를 사용하는 것이 좋다

-생성자는 부모꺼먼저 그리고 자식

-소멸자는 자식먼저 호출이 되고 부모

#include <iostream>
using std::cout;
using std::endl;
class A //할아버지
{
	int a;
public:
	A(int i) { a = i; }
	int getA() { return a; }
};
class B :public A //아버지
{
	int b;
public:
	B(int i, int j) :A(i) {
		// i는 기본 클래스 A의
		//생성자 매개변수로 전달됨
		b = j;
	}
	int getB() { return b; }
};
class C :public B //자식
{
	int c;
public:
	C(int i, int j, int k) :B(i, j) {
		// i, j는 클래스 B의 생성자 매개변수로 전달됨
		c = k;
	}
	void show() {
		cout << getA() << ' ' << getB() << ' ' << c << endl;
	}
};
int main()
{
	C cc(10, 20, 30);
	cc.show();
	cout << cc.getA() << ' ' << cc.getB() << endl;
	return 0;
}

다중상속의 접근 방식이 public상속

#include <iostream>
using std::cout;
using std::endl;
class A
{
protected: //private이라면?
	int a, b;
public:
	void setAB(int i, int j) { a = i; b = j; }
};
class B :public A
{
	int c; // private
public:
	void setC(int n) { c = n; }
	void showABC() { cout << a << b << c << endl; }
	//기본 클래스의 protected 멤버들은
	//파생 클래스의 멤버에 의해 접근될 수 있다.
};
int main()
{
	A aa;
	B bb;
	aa.a; //외부에서는 접근불가
	bb.b; //외부에서는 접근불가
	bb.setAB(1, 2);
	bb.setC(3);
	bb.showABC();
	return 0;
}

출처: 1학년 2학기 수업자료/  한성현 교수님

'C++프로그래밍' 카테고리의 다른 글

c++프로그래밍 15주차 과제  (0) 2023.12.13
C++프로그래밍 13주차 과제  (1) 2023.11.29
C++프로그래밍 11주차 과제  (0) 2023.11.15
c++프로그래밍 10주차 과제  (1) 2023.11.08
C++ 프로그래밍 9주차 과제  (0) 2023.11.01

객체 지향 언어의 3가지 중요한 특징:  캡슐화, 상속, 다형성

 

1. 캡슐화: 캡슐화는 객체의 데이터와 그 데이터를 처리하는 함수를 하나로 묶는 것을 말합니다. 

2. 상속: 상속은 기존의 클래스를 확장하여 새로운 클래스를 생성하는 것을 말합니다.

3. 다형성: 다형성은 같은 이름의 메서드가 다른 기능을 수행할 수 있도록 하는 것을 말합니다. 

<function overloading을 지원하는 프로그램이 언어>

1. C++

2. Java

3. Python

4. C#

overloading-> overridding

overloading(오버로딩): 이름이 같은 함수가 여러개 있다 (소스를 이해하기 쉬움)

 

#include <iostream>
int add(int i, int j)
{
	return (i + j);
}
double add(double i, double j)
{
	return (i + j);
}
int main()
{
	std::cout << add(10, 20) << std::endl;
	std::cout << add(10.5, 20.3) << std::endl;
	return 0;
}

 컴파일러가 매개변수의 입력 자료형에 따라서 자동적으로 해당 함수를 연결해준다.

 

#include <iostream>
int add(int i, int j)
{
	return (i + j);
}
double add(double i, double j)
{
	return (i + j);
}
double add(int i, int j)//매개변수가 같으면 오버로딩을 할 수 없다(오류)
{
	return ((double)i + (double)j);
}
int main()
{
	std::cout << add(10, 20) << std::endl;
	std::cout << add(10.5, 20.3) << std::endl;
	return 0;
}

 

C vs C++

//c
#include <iostream>
int add2(int i, int j)
{
return (i+j);
}
int add3(int i, int j, int k)
{
return (i+j+k);
}
int add4(int i, int j, int k, int l)
{
return (i+j+k+l);
}
int main()
{
std::cout<<add2(1,2)<<std::endl;
std::cout<<add3(1,2,3)<<std::endl;
std::cout<<add4(1,2,3,4)<<std::endl;
return 0;
} //오버로딩 안함
//C++
#include <iostream>
int add(int i, int j)
{
return (i+j);
}
int add(int i, int j, int k)
{
return (i+j+k);
}
int add(int i, int j, int k, int l)
{
return (i+j+k+l);
}
int main()
{
std::cout<<add(1,2)<<std::endl;
std::cout<<add(1,2,3)<<std::endl;
std::cout<<add(1,2,3,4)<<std::endl;
return 0;
} //오버로딩 함
#include <iostream>
int add(int i, int j)//매개변수의 형이 다른 경우
{
	return (i + j);
}
float add(float i, float j)//매개변수의 형이 다른 경우
{
	return (i + j);
}
double add(double i, double j)//매개변수의 형이 다른 경우
{
	return (i + j);
}
int add(int i, int j, int k)//  매개변수의 개수가 다른경우
{
	return (i + j + k);
}
int add(int i, int j, int k, int l)//  매개변수의 개수가 다른경우
{
	return (i + j + k + l);
}
int main()
{
	std::cout << add(1, 2) << std::endl;//매개변수의 형이 다른 경우
	std::cout << add(1.3f, 2.6f) << std::endl;//매개변수의 형이 다른 경우
	std::cout << add(6.5, 3.8) << std::endl;//매개변수의 형이 다른 경우
	std::cout << add(1, 2, 3) << std::endl;//  매개변수의 개수가 다른경우
	std::cout << add(1, 2, 3, 4) << std::endl;//  매개변수의 개수가 다른경우
	return 0;
}

매개변수의 형이 다른 경우와 매개변수의 개수가 다른경우에만 함수 중첩이 가능하다

가장 많이 쓰는 오버로딩: 생성자 오버로딩

//생성자 함수 중첩 예
#include <iostream>
class Dog {
private:
	int age;
public:
	Dog() { age = 1; } // 매개변수가 없는 생성자, 자동 inline
	Dog(int a) { age = a; } // 매개변수가 하나인 생성자
	~Dog();
	int getAge();
	void setAge(int a);
};
Dog::~Dog()
{
	std::cout << "소멸";
}
int Dog::getAge()
{
	return age;
}
void Dog::setAge(int a)
{
	age = a;
}
int main()
{
	Dog happy(2), meri;
	std::cout << happy.getAge() << "," << meri.getAge();
	return 0;
}

 

 

<디폴트 매개변수>

-별도의 매개변수를 전달하지 않아도 기본적인 값을 전달하도록 함수 원형을 선언할 때 디폴트 값을 지정할 수 있다

- 해당 매개변수가 주어지지 않으면 디폴트 인자 값이 할당된다

#include <iostream>
int add(int i=1, int j=2) // 형식매개변수
{
	return(i + j);
}
int main()
{
	std::cout << add() << ","; // 실매개변수 없음, 3
	std::cout << add(10) << ","; // 실매개변수 한 개, 12
	std::cout << add(10, 20); // 실매개변수 두개, 30
	return 0;
}

 

#include <iostream>
int add(int i = 1, int j = 2); // 형식매개변수

int main()
{
	std::cout << add() << ","; // 실매개변수 없음, 3
	std::cout << add(10) << ","; // 실매개변수 한 개, 12
	std::cout << add(10, 20); // 실매개변수 두개, 30
	return 0;
}
int add(int i, int j) //형식매개변수
{
	return(i + j);
}

디폴트 매개변수를 갖는 함수를 만들 때, main()함수 전에 함수 선언을 하면 선언부에만 디폴트 인자를 지정해야 한다.  int add(int i=1, int j=2);// 선언부에 디폴트 인자 작성

 

 디폴트 매개변수의 사용은 함수 중첩의 축약형이다.

#include <iostream>
class Dog {
private:
	int age;
public:
	Dog(int a=1) { age = a; }
	//Dog() { age = 1; }
	// 디폴트 매개변수를 갖는 생성자
	~Dog();
	int getAge();
	void setAge(int a);
};
Dog::~Dog(){std::cout << "소멸\n";}
int Dog::getAge(){return age;}
void Dog::setAge(int a){age = a;}
int main()
{
	Dog meri, happy(5);
	std::cout << happy.getAge() << "," <<
		meri.getAge() << std::endl;
	return 0;
}
#include <iostream>
class Dog {
private:
	int age;
public:
	Dog(int a = 1);//생성자가 밖으로 나와있을때 선언부에만 디폴트 인자를 쓴다
	//Dog() { age = 1; }
	// 디폴트 매개변수를 갖는 생성자
	~Dog();
	int getAge();
	void setAge(int a);
};
Dog::Dog(int a) { age = a; }//생성자가 밖으로 나와있을때 선언부에만 디폴트 인자를 쓴다
Dog::~Dog(){std::cout << "소멸\n";}
int Dog::getAge(){return age;}
void Dog::setAge(int a){age = a;}
int main()
{
	Dog meri, happy(5);
	std::cout << happy.getAge() << "," <<
		meri.getAge() << std::endl;
	return 0;
}
#include <iostream>
int Gop(int i, int j, int k = 1, int l = 1)
{
	return(i * j * k * l);
}
int main()
{
	std::cout << Gop(1, 2) << std::endl; // 1*2*1*1
	std::cout << Gop(1, 2, 3) << std::endl; // 1*2*3*1
	std::cout << Gop(1, 2, 3, 4) << std::endl;// 1*2*3*4
	return 0;
}

출처: 1학년 2학기 수업자료/ 한성현 교수님

'C++프로그래밍' 카테고리의 다른 글

C++프로그래밍 13주차 과제  (1) 2023.11.29
C++프로그래밍 12주차 과제  (1) 2023.11.22
c++프로그래밍 10주차 과제  (1) 2023.11.08
C++ 프로그래밍 9주차 과제  (0) 2023.11.01
C++ 프로그래밍 6주차 과제  (0) 2023.10.18
//변형 전
#define _CRT_SECURE_NO_WARNINGS
#include <iostream>
#include <string>
using std::cout;
class Cat {
private: //생략가능
	int age;
	char name[20];
	// const char* name; //A
public:
	Cat(int age, const char* n) {
		this->age = age;
		strcpy(name, n); // name=n; //A
		cout << name << "고양이 객체가 만들어졌어요.\n";
	}
	~Cat() { cout << name << "객체 바이\n"; };
	int getAge();
	const char* getName();
	void setAge(int age);
	void setName(const char* pName);
	void meow();
};
int Cat::getAge() {
	return age;
}
void Cat::setAge(int age) {
	this->age = age;
}
void Cat::setName(const char* pName) {
	strcpy(name, pName);
	//strcpy(대상주소, 원본주소);
	//strcpy_s(대상주소, 대상의길이, 원본주소);
	//name=pName; //A
}
const char* Cat::getName() {
	return name;
}
void Cat::meow() {
	cout << name << "고양이가 울어요\n";
}
int main() {
	Cat nabi(1, "나비"), yaong(1, "야옹"), * pNabi;
	cout << nabi.getName() << " 출생 나이는 " << nabi.getAge() << "살이다.\n";
	cout << yaong.getName() << " 출생 나이는 " << yaong.getAge() << "살이다.\n";
	pNabi = &nabi;
	cout << pNabi->getName() << " 출생 나이는 " << pNabi->getAge() << "살이다.\n";
	nabi.setName("Nabi");
	nabi.setAge(3);
	cout << nabi.getName() << " 나이는 " << nabi.getAge() << "살이다.\n";
	yaong.meow();
	nabi.meow();
	return 0;
}
//변형 후(1)
#define _CRT_SECURE_NO_WARNINGS
#include <iostream>
#include <string>
using std::cout;
class Cat {
private: //생략가능
	int age;
	std::string name;
	
public:
	Cat(int age, std::string n) {
		this->age = age;
		name= n; 
		cout << name << "고양이 객체가 만들어졌어요.\n";
	}
	~Cat() { cout << name << "객체 바이\n"; };
	int getAge();
	std::string getName();
	void setAge(int age);
	void setName(std::string pName);
	void meow();
};
int Cat::getAge() {
	return age;
}
void Cat::setAge(int age) {
	this->age = age;
}
void Cat::setName(std::string pName) {
	name=pName;

}
std::string Cat::getName() {
	return name;
}
void Cat::meow() {
	cout << name << "고양이가 울어요\n";
}
int main() {
	Cat nabi(1, "나비"), yaong(1, "야옹"), * pNabi;
	cout << nabi.getName() << " 출생 나이는 " << nabi.getAge() << "살이다.\n";
	cout << yaong.getName() << " 출생 나이는 " << yaong.getAge() << "살이다.\n";
	pNabi = &nabi;
	cout << pNabi->getName() << " 출생 나이는 " << pNabi->getAge() << "살이다.\n";
	nabi.setName("Nabi");
	nabi.setAge(3);
	cout << nabi.getName() << " 나이는 " << nabi.getAge() << "살이다.\n";
	yaong.meow();
	nabi.meow();
	return 0;
}

#define IN 1 // 컴파일 전에 IN을 찾아서 1로 바꿈
#include <iostream>
int main()
{
	const int x = 2; // 변수 x는 항상 1, 변경 불가, 초기값 지정해야
	int const y = 3; // 비추, const는 자료형 앞에 씀
	const int z{ 4 }; // Uniform initialization, C++11, z{}
	constexpr int a = 5; //C++11부터 가능, compile-time constant
	//x = 2; //변경 불가
	//y=10;
	//z= 20;
	//const지정을 하면 변경 불가
	std::cout << IN << x << y << z << a;
	return 0;
}

-멤버 변수를 변경하지 않는 함수는 뒤에 const를 쓴다

//오류 수정 전
#include <iostream>
class Dog {
	int age; //private 생략함
public:
	int getAge() const;
	void setAge(int a) { age = a; }
	void view() { std::cout << "나는 view"; }
};
int Dog::getAge() const
{
	view(); // 오류 ①
	return (++age); // 오류 ②
}
int main()
{
	Dog happy;
	happy.setAge(5);
	std::cout << happy.getAge();
	return 0;
}

//수정 후
#include <iostream>
class Dog {
	int age; //private 생략함
public:
	int getAge() const;
	void setAge(int a) { age = a; }
	void view() const
	{ 
		std::cout << "나는 view";
	}
};
int Dog::getAge() const
{
	view(); // 오류 ① view를 const로 지정해줘야지 호출 가능함
	return age; // 오류 ② 멤버 변수 age를 변경해서 나는 오류
}
int main()
{
	Dog happy;
	happy.setAge(5);
	std::cout << happy.getAge();
	return 0;
}

   

const함수는 const함수만 호출할 수 있으며 일반 멤버함수에는 접근할 수 없다.

#include <iostream>
class Dog {
	int age; //private 생략함
public:
	int getAge() const;
	void setAge(int a) {
		age = a;
	}//const는 반드시 지정할 필요는 없는데 쓰면 소스를 이해하는데 수월하다

	
};
int Dog::getAge() const
{
	
	return age; // 오류 ② 멤버 변수 age를 변경해서 나는 오류
}
int main()
{
	Dog happy;
	happy.setAge(5);
	std::cout << happy.getAge();
	return 0;
}
#include <iostream>
class Dog {
	int age; //private 생략함
public:
	int getAge() const;
	void setAge(int a) {
		age = a;
	}//const는 반드시 지정할 필요는 없는데 쓰면 소스를 이해하는데 수월하다

	
};

int main()
{
	Dog happy;
	happy.setAge(5);
	std::cout << happy.getAge();
	return 0;
}
#include <iostream>
int main()
{
	int array[1000000]; //4MB, 지역변수는 스택에 저장하는데 기본 스택 크기를 넘어서 오류
	std::cout << "aaaa";
	return 0;
}//VS에서 실행될까?

//동적 메모리 할당, 동적 메모리 할당

#include <iostream>
int main()
{
	int *pi = new int; // 동적 메모리 할당, heep
	int x; //정적 메모리 할당, 스택
	if (!pi) { // pi==0, 널 포인터인지 확인
		std::cout << "메모리할당이 되지 않았습니다.";
		return 1; //비정상 종료시 리턴값
	}
	*pi = 100; //주소의 값으로 100을 할당
	x = 10;
	std::cout << "동적메모리=" << *pi << ", x=" << x;
	delete pi; // 메모리 해제
	return 0; // 정상 종료시 리턴값
}

-대괄호 쓰는거 주의하기

-new를 사용하면 반드시 delete를 써야 한다 , 안쓰면 다른 프로그램에서 사용 불가

-배열의 이름은 배열의 시작 주소이다

ex} int x[3] ={1,2,3} 일때 x는 1이 저장된 곳의 주소

           x[0];//1

           x[1];//2

           x[2];//3

//실습과제
#define _CRT_SECURE_NO_WARNINGS
#include <iostream>
#include <string>
using std::cout;
class Cat {
private: //생략가능
	int age;
	std::string name;
public:
	Cat(int age, std::string n) {
		this->age = age;//int age;
		name = n;
		cout << name << "고양이 객체가 만들어졌어요.\n";
	}
	~Cat() { cout << name << "객체 바이\n"; }; //소멸자
	int getAge() const; //변경 안됨
	std::string getName()const;
	void setAge(int age);
	void setName(std::string pName);
	void meow()const;
};
int Cat::getAge() const {
	return age;
}
void Cat::setAge(int age) {
	this->age = age;
}
void Cat::setName(std::string pName) {
	name = pName;
}
std::string Cat::getName() const {
	return name;
}
void Cat::meow() const {
	cout << name << "고양이가 울어요\n";
}
int main() {
	Cat nabi(1, "나비"), yaong(1, "야옹"), * pNabi;
	cout << nabi.getName() << " 출생 나이는 " << nabi.getAge() << "살이다.\n";
	cout << yaong.getName() << " 출생 나이는 " << yaong.getAge() << "살이다.\n";
	pNabi = &nabi;
	cout << pNabi->getName() << " 출생 나이는 " << pNabi->getAge() << "살이다.\n";
	nabi.setName("Nabi");
	nabi.setAge(3);
	cout << nabi.getName() << " 나이는 " << nabi.getAge() << "살이다.\n";
	yaong.meow();
	nabi.meow();
	return 0;
}
#include <iostream>
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* dp;//배열의 이름은 배열의 시작 주소이다
	dp = new Dog[10]; // 객체배열 할당 배열을 동적으로 할당했을떄는 대괄호를 써야함
	// Dog *dp=new Dog[10];
	if (!dp) {
		std::cout << "메모리할당이 되지 않았습니다.";
		return 1;
	}
	for (int i = 0; i < 10; i++) // C++에서는 가능
		dp[i].setAge(i);
	for (int i = 0; i < 10; i++)
		std::cout << i << "번째 객체의 나이는 " <<
		dp[i].getAge() << " 입니다. " << std::endl;
	delete[]dp;
	return 0;
}

 출처: 1학년 2학기 수업자료 / 한성현 교수님

'C++프로그래밍' 카테고리의 다른 글

C++프로그래밍 12주차 과제  (1) 2023.11.22
C++프로그래밍 11주차 과제  (0) 2023.11.15
C++ 프로그래밍 9주차 과제  (0) 2023.11.01
C++ 프로그래밍 6주차 과제  (0) 2023.10.18
C++프로그래밍 5주차 과제  (1) 2023.10.11

#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>
class Dog {
private:
	int age;
public:
	int getAge() {
		return age;
	}
	void setAge(int a) {//return값이 없으면 void를 쓴다
		age = a;
	}
};
int main()
{
	Dog happy;
	happy.setAge(3);
	// happy.age = 3;
	std::cout << happy.getAge();
	return 0;
}

직접참조연산자 : . 

-일반 객체가 멤버(변수/함수)에 접근하기 위해 사용

 간접참조연산자 : ->

- 포인터 객체가 멤버(변수/함수)에 접근하기 위해 사용

//c++07 ppt 6p오류 수정 후

#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; // Dog class의 happy객체 정의

	happy.setAge(3); //  happy.setAge(3);
	cout << happy.getAge(); //cout<<happy.getAge()<<'\n';
	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; // Dog class의 happy객체 정의

	happy.setAge(3); //  happy.setAge(3);
	cout << happy.getAge(); //cout<<happy.getAge()<<'\n';
	happy.cry();
	return 0;
}

 

#include <iostream>
using std::cout;
class Dog {
private:
	int age;
public:
	int getAge();
	void setAge(int a);
	void cry();
};
void Dog:: cry() {
	cout << "멍멍~~\n";
}
int Dog::getAge()
{
	return age;
}
void Dog::setAge(int a)
{
	age = a;
}
int main()
{
	Dog happy; // Dog class의 happy객체 정의

	happy.setAge(3); //  happy.setAge(3);
	cout << happy.getAge(); //cout<<happy.getAge()<<'\n';
	happy.cry();
	return 0;
}

 

//7p //using namespace std;주석 처리 했을때, string, cout 앞에 std::붙이기
#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;
}

문자열을 복사할떄는 strcpy형태를 사용한다

 

//배열 복사는 strcpy() 사용
#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;
}

 배열을 복사할 떄는 strcpy로 string형을 쓸때는 그냥 대입하면 된다.

//문자 or 문자열 리턴 자판기 함수 35p
#include <iostream>
//using namespace std;
char vending(int x)
{
	if (x == 1) return 'A';
	else return 'B';
}
std::string vending1(int x)
{
	if (x == 1) return "커피";
	else return "우유";
}
int main()
{
	std::cout << vending(1);
	std::cout << vending1(1);
	return 0;
}

int자리에 const char *를 써주면 문자열을 리턴하는게 가능하다

p38
#define _CRT_SECURE_NO_WARNINGS
#include <iostream>
#include <string>
using namespace std; //C
class Cat {
private: //생략가능
	int age;
	std::string name; // A
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;
}
//p39
#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(1);
		cout << dd[i].getAge(); //01234
	}
	return 0;
}
//p40
#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);
	cout << happy.getAge() << pd->getAge();
	return 0;
}

 

 

 

p48
#include <iostream>
using std::cout;
class Dog {
private:
	int age;
public:
	//Dog(){age = 1;} //아래 두개 포함해서 3개는 같은 소스이다
	//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();
	cout << happy1.getAge();
	return 0;
}
#include <iostream>
using std::cout;
class Dog {
private:
	int age;
public:
	Dog(){age = 1;}
	int getAge() { return age; }
	void setAge(int a) { age = a; }
};
int main()
{
	Dog happy, happy1; //happy객체가 생성되는 순간 생성자가 자동 호출됨
	cout << happy.getAge();
	cout << happy1.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; 
}
int Dog::getAge() { return age; }
void Dog::setAge(int a) { age = a; }
int main()
{
	Dog happy; //happy객체가 생성되는 순간 생성자가 자동 호출됨
	cout << happy.getAge();
	return 0;
}
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;
}
#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;
}

 

출처: 1학년 2학기 수업자료 한성현 교수님/

'C++프로그래밍' 카테고리의 다른 글

C++프로그래밍 11주차 과제  (0) 2023.11.15
c++프로그래밍 10주차 과제  (1) 2023.11.08
C++ 프로그래밍 6주차 과제  (0) 2023.10.18
C++프로그래밍 5주차 과제  (1) 2023.10.11
C++ 프로그래밍 4주차 과제  (0) 2023.09.27
struct Man {
    int age;
    double weight;
};
#include <iostream>

int main()
{
    Man han; //c언어에서는 struct써야함
    han.age = 10;
    han.weight = 20.5;

    std::cout << han.age <<"  "<<han.weight << std:: endl;
}

* class명 : Integer

* 객체명 : Val2

 

*class멤버의 접근 방법이 3가지가 있다 

private (protected) : 해당 클래스 내부에만 접근 가능 (디폴트 속성으로 생략 가능)

public은 어디서나 접근 가능

*노란 표시 : 기본 접근 속성(생략 가능)

 

감추고 싶으면 private;

*누구나 접근 가능(문)

#include <iostream>
class Man {
private:
    
    int age;
    double weight;
public:
    int getAge() {
        return age;
    }
   void setAge(int a) {
        age = a;
    }
   double getWeight() {
       return weight;
   }
   void setWeight(double w) {
       weight = w;
   }
};


int main()
{
    Man han; //c언어에서는 struct써야함
  //  han.age = 10; //'Man::age' : private 멤버('Man' 클래스에서 선언)에 액세스할 수 없습니다.
    han.setAge(5); //5살이야
    han.setWeight(30.5);
    std::cout << han.getAge() <<"   "<< han.getWeight() << std::endl;
}

*class diagram

class 이름: Man
멤버 변수 : -age : int
                  -weight : double
+ getAge() , +setAge(),
+ getWeight(), + setWeigth()

 

#include <iostream>
class Man {
private:
    
    int age;
    double weight;
public:
    int getAge();
    void setAge(int a);
    double getWeight();
    void setWeight(double w);
};

int Man::getAge() { //소속을 밝혀야함 Man::
    return age;
}
void Man::setAge(int a) {
    age = a;
}
double Man:: getWeight() {
    return weight;
}
void Man:: setWeight(double w) {
    weight = w;
}

int main()
{
    Man han; //c언어에서는 struct써야함
  //  han.age = 10; //'Man::age' : private 멤버('Man' 클래스에서 선언)에 액세스할 수 없습니다.
    han.setAge(5); //5살이야
    han.setWeight(30.5);
    std::cout << han.getAge() <<"   "<< han.getWeight() << std::endl;
}

*밖으로 내보낼때는 소속을 적어야함

*  '::' 연산자(범위 지정 연산자) : 어떤 클래스 소속인지 나타낼때/ 변수 앞에 ::을 찍으면 지역변수가 아닌 전역변수를 접근할 떄 씀

<inline함수>

#include<iostream>
using std::cout;
#define sum(i, j) (i + j) // 매크로함수
inline int iSum
(int i, int j) // inline 함수, 속도 빨리
{
	return i + j;
}
int add(int i, int j) // 일반 함수
{
	return i + j;
}
int main() {
		cout << sum(10, 20) /2 << ","; //10+20/2, 매크로함수의 부작용
		cout <<iSum(10, 20) /2 << ","; //(10+20) /2
		cout << add(10, 20) /2; //(10+20) /2
		return 0;
}

*멤버 함수를 클래스 내부에 정의하면 자동 inline함수가 된다.

//수정전
#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; // Dog class의 happy객체 정의
	Dog.age=2; //① Dog는 class
	happy.age=3; //② age는 private멤버로 클래스 밖에서 접근 불가
	cout << happy.age; //③ age는 전용멤버로 접근 불가
		return 0;
		
		
}



//수정후
#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; // Dog class의 happy객체 정의

	happy.setAge(3); //② age는 private멤버로 클래스 밖에서 접근 불가
	cout << happy.getAge(); //③ age는 전용멤버로 접근 불가
	return 0;
		
		
}

출처: 1학년 2학기 수업자료 한성현 교수님 /   smile han https://www.youtube.com/@smilehan8416

'C++프로그래밍' 카테고리의 다른 글

c++프로그래밍 10주차 과제  (1) 2023.11.08
C++ 프로그래밍 9주차 과제  (0) 2023.11.01
C++프로그래밍 5주차 과제  (1) 2023.10.11
C++ 프로그래밍 4주차 과제  (0) 2023.09.27
C++프로그래밍 3주차 과제  (1) 2023.09.20

+ Recent posts