하나의 객채를 여러 개채가 공유해야 할때 어떻게 하나요???

jic5760의 이미지

class Parent {
 protected int m_a;
}
 
class Child1 : Parent {
 private int m_b;
 
 void func(){
  this.m_b = base.m_a; // m_a 접근가능
 }
}
 
class Child2 : Parent {
 private int m_c;
 
 void func(){
  this.m_c = base.m_a; // m_a 접근가능
 }
}

간단하게 이런 코드가 있을 때 Child1, Chile2에서 같은 Parent 객체를 공유하고 싶습니다.

Parent p = new Parent();
Child1 c1 = (Child1)p;
Child2 c2 = (Child2)p;
 
// p.m_a 접근못함.

뭐 이런 개념인데 이런건 안되자나요..ㅠㅠ

Child가 아닌 다른 곳에서는 Parent의 protected을 사용하지 못하고
Child에서만 Parent의 protected을 사용하고 싶은데 방법을 모르겠습니다..ㅠㅠ

이런 경우에는 어떻게 해야 하나요?

일단 지금은

class Parent {
 protected int m_a;
 
 public Parent(Parent me)
 {
  this.m_a = me.m_a; // 복사
 }
}
 
class Child1 : Parent {
 private int m_b;
 
 public Child2(Parent parent) : base(parent)
 {
 
 }
 
 void func(){
  this.m_b = base.m_a; // m_a 접근가능
 }
}
 
class Child2 : Parent {
 private int m_c;
 
 public Child2(Parent parent) : base(parent)
 {
 
 }
 
 void func(){
  this.m_c = base.m_a; // m_a 접근가능
 }
}
 
 
 
Parent p = new Parent();
Child1 c1 = new Child1(p);
Child2 c2 = new Child2(p);

이런식으로 하고 있는데 이러면 완전한 공유가 되지 않아서..ㅜㅜ
HDNua의 이미지

1. 프로그래밍 언어는 C#을 쓰신다고 생각하겠습니다.
Child가 아닌 다른 곳에서는 Parent의 protected을 사용하지 못하고 Child에서만 Parent의 protected을 사용하고 싶다고 하셨는데,
protected 자체가 이미 자신과 자신의 하위 객체 내부에서만 자유로이 접근하게 만드는 보호 수준입니다.
protected나 스코프(scope)로 검색하셔서 더 알아보셔요.
https://msdn.microsoft.com/query/dev14.query?appId=Dev14IDEF1&l=KO-KR&k=k(protected_CSharpKeyword);k(TargetFrameworkMoniker-.NETFramework,Version%3Dv4.5.2);k(DevLang-csharp)&rd=true

3. protected랑은 별 관련이 없이, 단 하나만 존재하는 객체의 값을 공유하기 위해 당장 떠오르는 방법은 두 가지입니다.
3.1) static field

using System;
 
class Parent
{
    protected static int _field; // static 멤버 변수 정의
}
class Child1 : Parent
{
    public int FieldValue()
    {
        return _field;
    }
    public void SetFieldValue(int value)
    {
        _field = value;
    }
}
class Child2 : Parent
{
    public int FieldValue()
    {
        return _field;
    }
    public void SetFieldValue(int value)
    {
        _field = value;
    }
}
 
class Program
{
    public static void Main(string[] args)
    {
        Parent p = new Parent();
        Child1 c1 = new Child1();
        Child2 c2 = new Child2();
 
        c1.SetFieldValue(10);
        Console.WriteLine("{0}/{1}", c1.FieldValue(), c2.FieldValue());
        c2.SetFieldValue(20);
        Console.WriteLine("{0}/{1}", c1.FieldValue(), c2.FieldValue());
    }
}

3.2) singleton

using System;
 
class Singleton
{
    // 싱글톤 인스턴스 포인터
    static Singleton _instance;
 
    // 인스턴스에 대한 프로퍼티
    public static Singleton Instance
    {
        get
        {
            // 두 개 이상의 Singleton 객체를 생성할 수 없도록 함
            if (_instance == null)
                _instance = new Singleton();
            return _instance;
        }
    }
 
    // 싱글톤 필드 & 프로퍼티
    public int Field { get; set; }
}
class Object1
{
    public int FieldValue()
    {
        return Singleton.Instance.Field;
    }
    public void SetFieldValue(int value)
    {
        Singleton.Instance.Field = value;
    }
}
class Object2
{
    public int FieldValue()
    {
        return Singleton.Instance.Field;
    }
    public void SetFieldValue(int value)
    {
        Singleton.Instance.Field = value;
    }
}
 
class Program
{
    public static void Main(string[] args)
    {
        Object1 o1 = new Object1();
        Object2 o2 = new Object2();
 
        o1.SetFieldValue(10);
        Console.WriteLine("{0}/{1}", o1.FieldValue(), o2.FieldValue());
        o2.SetFieldValue(20);
        Console.WriteLine("{0}/{1}", o1.FieldValue(), o2.FieldValue());
    }
}

답변을 달고 보니 질문의 의도와 맞지 않았을지도 모르겠다는 생각도 드네요.
다른 분들의 답변도 들어보시는 것이 좋을 거라 생각합니다.

저는 이렇게 생각했습니다.

댓글 달기

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
이것은 자동으로 스팸을 올리는 것을 막기 위해서 제공됩니다.