pointer 사용

😎·2022년 11월 29일
0

CPP

목록 보기
11/46

pointer

내가 느끼기에 포인터 사용은 C 와 다르지 않다고 느꼈다. 물론... 아직까지는 말이다.
그래서 간단하게 예시 코드만 남긴다.


예시

  • Sample.class.hpp
#ifndef SAMPLE_CLASS_H
# define SAMPLE_CLASS_H

class Sample {
    public:
        int foo;

        Sample(void);
        ~Sample(void);

        void bar(void) const;
};

#endif
  • Sample.class.cpp
#include <iostream>
#include "Sample.class.hpp"

Sample::Sample(void) : foo(0) {
    std::cout << "Constructor caled" << std::endl;

    return;
}

Sample::~Sample(void) {
    std::cout << "Destructor called" << std::endl;
    return;
}

void Sample::bar(void) const {
    std::cout << "Member function bar called" << std::endl;
    return;
}
  • main.cpp
#include <iostream>
#include "Sample.class.hpp"

int main() {
    Sample instance;
    Sample *instancep = &instance;

    int Sample::*p = NULL;
    void (Sample::*f)(void) const;

    p = &Sample::foo;
    std::cout << "Value of member foo : " << instance.foo << std::endl;
    instance.*p = 21;
    std::cout << "Value of member foo : " << instance.foo << std::endl;
    instancep->foo = 42;
    std::cout << "Value of member foo : " << instance.foo << std::endl;

    f = &Sample::bar;

    (instance.*f)();
    (instancep->*f)();
    return 0;
}

profile
jaekim

0개의 댓글