3. C++

3.1. 클래스를 이용해서 호스트 이름 출력

g++ 을 이용해서 호스트 이름을 출력하는 테스트 프로그램입니다.

컴파일 : g++ -o test test.cpp

소스
#include <unistd.h>
#include <string>

// 클래스를 선언하나.
class Init
{
private:
public:
  static string get_hostname();
};

// get_hostname 이라는 함수를 만들어 준다.
string Init::get_hostname()
{
  char buf[128]; // 호스트 이름이 들어갈 변수를 선언
  string ret; 

  // 호스트 이름을 얻는 함수를 호출한다.
  if((gethostname ( buf, sizeof(buf) )) < 0) 
  {
    ret.assign("Unkown Hostname"); // 호스트 이름이 없을 경우
  } else 
  {
    ret.assign(buf); // 호스트 이름을 얻었을 경우
  }

  return ret;  // 결과 값을 리턴한다.
}

int main(void) 
{

  cout << Init::get_hostname() << endl; // 화면에 출력한다.

}
    

3.2. 객체 만들어서 출력하기

소스
#include <string>

// Hello 객체를 만든다.
class Hello 
{
  private:
  public:
    // 함수를 하나 만든다.
    void displayData() 
    {
      cout << "I am class" << endl; // 출력을 한다.
    }
};

int main(void)
{
  Hello hello; //hello 객체를 선언한다.

  hello.displayData(); //출력한다.
}
    

결과
I am class