엔지니어가 되고 싶은 공돌이
10. Struct Code 본문
- C++ struct
#include <iostream> // 구조체, 접근방법, 할당
using namespace std;
struct Accnt{
int number; // 계좌번호
char name[10]; // 예금주
double value; // 잔액
};
int main()
{
Accnt p1, p2; //struct Accnt p1, p2;
//입력
cout << "ID=? ";
cin >> p1.number;
cout << "Name=? ";
cin >> p1.name;
cout << "Balance=? ";
cin >> p1.value;
p2 = p1;
//출력
cout << "ID= "<< p2.number << endl;
cout << "Name= "<< p2.name << endl;
cout << "Balance= "<< p2.value << endl;
return 0;
}
- Function & struct
#include <iostream> // 함수의 매개변수, 리턴값
// 함수의 레퍼런스
using namespace std;
struct Accnt{
int number; //계좌번호
char name[10]; //예금주
double value; //잔액
}; // } p1, p2;
//void Input_Accnt(Accnt &p);
Accnt Input_Accnt();
void output_Accnt(Accnt p);
int main()
{
Accnt p1, p2; // struct Accnt p1, p2;
//입력
//Input_Accnt(p1);
p1 = Input_Accnt();
p2 = p1;
//출력
output_Accnt(p2);
return 0;
}
//void Input_Accnt(Accnt &p) // call-by-reference
Accnt Input_Accnt()
{
Accnt p;
cout << "ID = ?";
cin >> p.number;
cout << "Name = ?";
cin >> p.name;
cout << "Balance = ?";
cin >> p.value;
return p;
}
void output_Accnt(Accnt p)
{
cout << "ID = " << p.number << endl;
cout << "Name = " << p.name << endl;
cout << "Balance = " << p.value << endl;
}
- struct function
#include <iostream> // 구조체 + 입력, 출력 추가
using namespace std;
struct Accnt{
int number; //계좌번호
char name[10]; //예금주
double value; //잔액
void Input_Accnt(){
cout << "ID = ?";
cin >> number; // cin >> p1.number; 오류:구조체 정의에 구조체 특정변수를 포함
cout << "Name = ?";
cin >> name;
cout << "Balance = ?";
cin >> value;
}
void add_value(int a){
value += a;
}
int get_value(){
return value;
}
void output_Accnt(){
cout << "ID = " << number << endl;
cout << "Name = " << name << endl;
cout << "Balance = " << value << endl;
}
};
int main()
{
Accnt p1, p2; // struct Accnt p1, p2;
//입력
p1.Input_Accnt();
p2.Input_Accnt();
//잔액 증가
int a=50;
p1.add_value(a);
//잔액 가져오기
int b;
b=p1.get_value();
cout << b << endl;
//출력
p1.output_Accnt();
p2.output_Accnt();
return 0;
}
'C++ Language > Base C++' 카테고리의 다른 글
12. Constructor (0) | 2021.04.07 |
---|---|
11. Class Code (0) | 2021.04.06 |
09. Array Code (0) | 2021.04.04 |
08. Class (0) | 2021.04.03 |
07. Structure (0) | 2021.04.02 |
Comments