반응형

5.7> 클래스 Accumulator add() 함수를 통해 계속 값을 누적하는 클래스로서, 다음과 같이 선언된다. Accumulator 클래스를 구현하라.


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
#include <iostream>
 
using namespace std;
 
class Accumulator{
private:
    int value;
public:
    Accumulator(int value);//매개 변수 value 로 멤버 value 초기화
    Accumulator& add(int n); //vlaue에 n을 더해 값 누적
    int get(); //누적된 값 value 리턴
};
Accumulator::Accumulator(int value){
    this->value=value; //value 값 이니셜라이징
}
Accumulator& Accumulator::add(int n){
    value+=n;
    return *this//리턴타입이 참조이다. this는 포인터이므로 역참조 연산자를 통해
                //참조를 리턴할 수 있다.
}
int Accumulator::get(){
    return value; //총더해진 값을 리턴
}
 
int main(void){
    Accumulator acc(10); //초기값 10
    acc.add(5).add(6).add(7); //5,6,7을 차례로 더한다
    cout<<acc.get(); //최종 더해진 값 리턴 (즉 28)
    return 0;
}
 
cs




반응형

'컴퓨터 & 프로그래밍 & 전자공학 > C++' 카테고리의 다른 글

모스 부호  (0) 2017.11.09
Book 클래스  (1) 2017.11.09
MyIntStack 클래스  (0) 2017.11.09
포인터의 증감  (0) 2017.11.09
변수와 포인터와 참조  (0) 2017.11.08
반응형
1
2
3
4
5
6
7
8
9
10
11
12
13
14
#include <iostream>
 
using namespace std;
 
int main(void){
    int a;
    int &b=a;
    int *c=&a;
    a=7;
    cout<<"a="<<a<<" b="<<b<<" *c="<<*c<<endl;
    cout<<"&a="<<&a<<" &b="<<&b<<" c="<<c<<endl;
 
    return 0;
}
cs






a는 int형 변수
b는 a의 별명(레퍼런스, 참조)
c는 a를 가리키는 포인터 변수
즉 a와 b와 *c는 같을 것이고
&a 와 &b와 c는 같을 것이다.
헷갈리지 말자~!


반응형

+ Recent posts