[C++] 다른 객체의 private 맴버 접근

gurumong의 이미지

책의 예제를 보다가 의문점이 있어 질문드립니다
아래 코드를 보면 Vector sum로 객체를 생성하고
해당객체의 이름으로 private 맴버를 sum.x, sum,y 등으로 접근하는데요
원래 public 맴버에만 접근 해야하는것이 아닌가요?

//Vector 클래스의 메서드 정의 파일

// vector.cpp -- Vector 클래스를 위한 메서드 
#include <iostream>
#include <cmath>
using namespace std;
#include "vector.h"
 
namespace VECTOR
{     
 
  ...
 
  // 두 Vector 객체를 더한다
  Vector Vector::operator+(const Vector & b) const
  {
    //return Vector(x + b.x, y + b.y);
 
    Vector sum;
    sum.x = x + b.x; // 객체의 private 맴버변수에 접근!?
    sum.y = y + b.y; // 마찬가지!?
    sum.set_ang();   // 마찬가지!?
    sum.set_mag();   // 마찬가지!?
    return sum;
  } 
 
  // Vector 객체 a에서 Vector 객체 b를 뺀다
  Vector Vector::operator-(const Vector & b) const
  {
    return Vector(x - b.x, y - b.y);
  } 
 
  ...
} 

//Vector 클래스의 선언
여기에 보면 분명 x, y등은 private 맴버거든요

// vector.h -- 모드 상태와 <<를 사용하는, Vector 클래스
#ifndef VECTOR_H_
#define VECTOR_H_
namespace VECTOR
{
  class Vector
  {
  private:
    double x;   // 수평 성분 
    double y;   // 수직 성분
    double mag; // 벡터의 길이
    double ang; // 벡터의 방향
    char mode;  // 'r' = 직각 좌표, 'p' = '극 좌표
    // 값들을 설정하는 private 메서드들
    void set_mag();
    void set_ang();
    void set_x();
    void set_y();
  public:
    Vector();
    Vector(double n1, double n2, char form = 'r');
    void set(double n1, double n2, char form = 'r');
    ~Vector();
    double xval() const {return x;}     // x값을 보고한다
    double yval() const {return y;}     // y값을 보고한다
    double magval() const {return mag;} // 크기를 보고한다
    double angval() const {return ang;} // 각도를 보고한다 
    void polar_mode(); // 모드를 'p'로 설정한다
    void rect_mode();  // 모드를 'r'로 설정한다
    // 연산자 오버로딩
    Vector operator+(const Vector & b) const;
    Vector operator-(const Vector & b) const;
    Vector operator-() const;
    Vector operator*(double n) const;
    // 프렌드 함수
    friend Vector operator*(double n, const Vector & a);
    friend ostream & operator<<(ostream & os, const Vector & v);
  };
}
 
#endif
winner의 이미지

실제로 접근이 안 되는 언어도 있지만 대부분 됩니다.
장단점이 있겠는데 장점 중 하나로 덕분에 get, set이 적게 필요합니다.

yielding의 이미지

copy constructor, assignment operator도 생각해보면 동일 타입의 데이타를 인자로 받아서 private member를 access하지요? 원래 문법에서 이렇게 허용합니다.
만약에 vector가 아니고 다른 class라면 setter, getter를 써서 접근을 해야겠죠.

Life rushes on, we are distracted

Life rushes on, we are distracted

ssehoony의 이미지

이 부분이 private 멤버에 대해 약간 혼란 스러운 부분인데요.
C++의 경우는 다른 인스턴스라도 동일한 클래스 일 경우는 private 멤버를 직접 접근 할 수 있습니다.
언어에 따라서는 인스턴스가 다르면 private 멤버에 접근을 못하도록 하는 경우도 있는데요.
c++은 동일 클래스이면 접근이 가능합니다.
동일 클래스라도 인스턴스가 다른면 private 멤버에 접근 못하는게 좋지 않냐라는 의견이 있는데요.
생각하기 나름이고, 정답이라는게 없는 상황이죠.

댓글 달기

Filtered HTML

  • 텍스트에 BBCode 태그를 사용할 수 있습니다. URL은 자동으로 링크 됩니다.
  • 사용할 수 있는 HTML 태그: <p><div><span><br><a><em><strong><del><ins><b><i><u><s><pre><code><cite><blockquote><ul><ol><li><dl><dt><dd><table><tr><td><th><thead><tbody><h1><h2><h3><h4><h5><h6><img><embed><object><param><hr>
  • 다음 태그를 이용하여 소스 코드 구문 강조를 할 수 있습니다: <code>, <blockcode>, <apache>, <applescript>, <autoconf>, <awk>, <bash>, <c>, <cpp>, <css>, <diff>, <drupal5>, <drupal6>, <gdb>, <html>, <html5>, <java>, <javascript>, <ldif>, <lua>, <make>, <mysql>, <perl>, <perl6>, <php>, <pgsql>, <proftpd>, <python>, <reg>, <spec>, <ruby>. 지원하는 태그 형식: <foo>, [foo].
  • web 주소와/이메일 주소를 클릭할 수 있는 링크로 자동으로 바꿉니다.

BBCode

  • 텍스트에 BBCode 태그를 사용할 수 있습니다. URL은 자동으로 링크 됩니다.
  • 다음 태그를 이용하여 소스 코드 구문 강조를 할 수 있습니다: <code>, <blockcode>, <apache>, <applescript>, <autoconf>, <awk>, <bash>, <c>, <cpp>, <css>, <diff>, <drupal5>, <drupal6>, <gdb>, <html>, <html5>, <java>, <javascript>, <ldif>, <lua>, <make>, <mysql>, <perl>, <perl6>, <php>, <pgsql>, <proftpd>, <python>, <reg>, <spec>, <ruby>. 지원하는 태그 형식: <foo>, [foo].
  • 사용할 수 있는 HTML 태그: <p><div><span><br><a><em><strong><del><ins><b><i><u><s><pre><code><cite><blockquote><ul><ol><li><dl><dt><dd><table><tr><td><th><thead><tbody><h1><h2><h3><h4><h5><h6><img><embed><object><param>
  • web 주소와/이메일 주소를 클릭할 수 있는 링크로 자동으로 바꿉니다.

Textile

  • 다음 태그를 이용하여 소스 코드 구문 강조를 할 수 있습니다: <code>, <blockcode>, <apache>, <applescript>, <autoconf>, <awk>, <bash>, <c>, <cpp>, <css>, <diff>, <drupal5>, <drupal6>, <gdb>, <html>, <html5>, <java>, <javascript>, <ldif>, <lua>, <make>, <mysql>, <perl>, <perl6>, <php>, <pgsql>, <proftpd>, <python>, <reg>, <spec>, <ruby>. 지원하는 태그 형식: <foo>, [foo].
  • You can use Textile markup to format text.
  • 사용할 수 있는 HTML 태그: <p><div><span><br><a><em><strong><del><ins><b><i><u><s><pre><code><cite><blockquote><ul><ol><li><dl><dt><dd><table><tr><td><th><thead><tbody><h1><h2><h3><h4><h5><h6><img><embed><object><param><hr>

Markdown

  • 다음 태그를 이용하여 소스 코드 구문 강조를 할 수 있습니다: <code>, <blockcode>, <apache>, <applescript>, <autoconf>, <awk>, <bash>, <c>, <cpp>, <css>, <diff>, <drupal5>, <drupal6>, <gdb>, <html>, <html5>, <java>, <javascript>, <ldif>, <lua>, <make>, <mysql>, <perl>, <perl6>, <php>, <pgsql>, <proftpd>, <python>, <reg>, <spec>, <ruby>. 지원하는 태그 형식: <foo>, [foo].
  • Quick Tips:
    • Two or more spaces at a line's end = Line break
    • Double returns = Paragraph
    • *Single asterisks* or _single underscores_ = Emphasis
    • **Double** or __double__ = Strong
    • This is [a link](http://the.link.example.com "The optional title text")
    For complete details on the Markdown syntax, see the Markdown documentation and Markdown Extra documentation for tables, footnotes, and more.
  • web 주소와/이메일 주소를 클릭할 수 있는 링크로 자동으로 바꿉니다.
  • 사용할 수 있는 HTML 태그: <p><div><span><br><a><em><strong><del><ins><b><i><u><s><pre><code><cite><blockquote><ul><ol><li><dl><dt><dd><table><tr><td><th><thead><tbody><h1><h2><h3><h4><h5><h6><img><embed><object><param><hr>

Plain text

  • HTML 태그를 사용할 수 없습니다.
  • web 주소와/이메일 주소를 클릭할 수 있는 링크로 자동으로 바꿉니다.
  • 줄과 단락은 자동으로 분리됩니다.
댓글 첨부 파일
이 댓글에 이미지나 파일을 업로드 합니다.
파일 크기는 8 MB보다 작아야 합니다.
허용할 파일 형식: txt pdf doc xls gif jpg jpeg mp3 png rar zip.
CAPTCHA
이것은 자동으로 스팸을 올리는 것을 막기 위해서 제공됩니다.