728x90
- 파이썬 튜터 (https://pythontutor.com/) - 소스를 시각화 해서 보여줌
- C++스타일 문자열 출력
#include <iostream>
void display(void); //선언, 프로토타입(prototype), 원형
void doubleNum(int x);
int doubleNumReturn(int x);
int add(int x, int y);
char vending(int x);
const char* vending1(int x);
std::string vending2(int x); //string형을 사용함. 스텐다드 동네에 있는 string형을 사용한다.
int main()
{
display(); //호출, call
doubleNum(10);
std::cout << doubleNumReturn(20);
std::cout << add(2, 3);
std::cout << vending(1);
std::cout << vending1(0); //벤딩1함수 호출
std::cout << vending2(1);
}
void doubleNum(int x)
{
std::cout << x * 2;
}
int doubleNumReturn(int x)
{
return x * 2;
}
int add(int x, int y)
{
return x + y;
}
char vending(int x)
{
if (x == 1) return 'A';
else return 'B';
}
const char* vending1(int x) //const char* c언어 스타일
{
if (x == 1) return "커피";
else return "코코아";
}
std::string vending2(int x) //std::string c++ 스타일
{
if (x == 1) return "콜라";
else return "사이다";
}
void display(void) //정의
{
std::cout << "강윤서\n";
}
- struct
#include <iostream>
struct Man {
int age; //멤버
double weight; //멤버
};
int main()
{
int x = 10;
std::cout << x << std::endl;//다음 줄로 넘기기
struct Man kang;
kang.age = 21;
std::cout << kang.age << std::endl;
kang.weight = 50;
std::cout << kang.weight << std::endl;
}
※ C와 C++의 차이점 - c++에서는 struct를 생략 가능하다
#include <iostream>
struct Man {
int age; //멤버
double weight; //멤버
};
int main()
{
int x = 10;
std::cout << x << std::endl;
Man kang; //struct를 없애도 정상 작동됨. 생략 가능
kang.age = 21;
std::cout << kang.age << std::endl;
kang.weight = 50;
std::cout << kang.weight << std::endl;
}
- 묶어서 사용
#include <iostream>
struct Man {
int age; //멤버
double weight; //멤버
};
int main()
{
Man kang = {20, 50.1}; //묶어서 사용하기
std::cout << kang.age << " " << kang.weight << std::endl;
kang.age = 21;
std::cout << kang.age << std::endl;
kang.weight = 50;
std::cout << kang.weight << std::endl;
}
- 문자열까지
#include <iostream>
struct Man {
int age; //멤버
double weight; //멤버
std::string name;
};
int main()
{
Man kang = {20, 50.1, "강강윤서"}; //묶어서 사용하기
std::cout << kang.name << " " << kang.age << " " << kang.weight << std::endl;
//"강강윤서"를 넣어 초기화를 해주지 않으면 자동 null들어가서 아무것도 출력되지 않음
kang.age = 21;
kang.weight = 50;
kang.name = "강윤서";
std::cout << kang.name << " " << kang.age << " " << kang.weight << std::endl;
}
- c++에서는 멤버 함수만 가능하다.
728x90
'C++' 카테고리의 다른 글
5-2 객체지향 프로그래밍 (0) | 2023.10.12 |
---|---|
5-1 구조체 (2) | 2023.10.11 |
4-1 함수(funtion) (0) | 2023.09.27 |
2-1 C문법 정리 (0) | 2023.09.13 |
1-1 C++개요 (0) | 2023.09.13 |