재귀 클래스, 클래스 함수 재귀에 관해 질문 드립니다.

trick9999의 이미지

안녕하세요. 계속 눈팅만하다가 이번에 처음으로 글을 써봅니다.

학생 클래스를 만들고
내부에 이름, 주소, 연락처를 만듭니다.
또한 멤버로 학생클래스 벡터 형태의 친구들을 둡니다.
그리고 이를 통해 친구 관계가 형성됩니다.

class Student {
public :
    Student() {}
    Student(string name, string address, string phone_number) {
        student_name = name;
        student_address = address;
        student_phone_number = phone_number;
    }
 
    string getName()                         { return student_name ; }
    void setName(string name)                { student_name = name; }
    string getAddress()                      { return student_address; }
    void setAddress(string address)          { student_address = address; }
    string getPhoneNumber()                  { return student_phone_number; }
    void setPhoneNumber(string phone_number) { student_phone_number = phone_number; }
 
    bool operator==(const Student &students);
 
    bool make_friends(const Student &students);
    void display_friends();
    <span>void make_connection();</span>
    void display_connection();
    vector<Student> connection;
private :
    string student_name;
    string student_address;
    string student_phone_number;
    vector<Student> friends;
    void sort_friends();
};

이러한 친구 관계를 이용해 자기가 알아낼 수 있는 모든 연락처를 알아내어 연락망을 만들고자 합니다.
우선 A의 친구인 B의 친구인 C의 친구인 . . . W의 친구인 X의 친구들(연락처)을 알아낸 다음
X의 친구인 W는 그것을 자신의 연락망에 추가하고
W의 친구인 V는 W의 연락망을 자신의 연락망에 추가하고 . .
이런 연락망이 누적되어 최종적으로 그 모든 연락처를 조합해 자신의 연락망을 완성하는 방식입니다.

void Student::make_connection() {
    unsigned int i, j, k;
    for(i = 0; i < friends.size(); i++) {
<span>//        cout << friends[i].getName() << endl;</span>
<span>        friends<span>.make_connection();</span>
[i]//        cout << friends[i].getName() << endl;</span>
        // 기존의 친구들의 목록을 더한다. 
        if(connection.empty())
            connection.push_back(friends[i]);
        else {
            for(j = 1; j < connection.size(); j++) {
                if(friends[i] == connection[j]) {
                    break;
                }
            }
            if((j-1) == connection.size())
                connection.push_back(friends[i]);
        }
 
<span>        // 자신의 연락망에 친구들의 연락망을 참조해 추가한다. 
        cout << friends[i].connection.size() << endl;
        for(j = 0; j < friends[i].connection.size(); j++) {
            cout << friends.size() << endl;
            // 친구의 연락망 중 자신의 연락망과 중복된 것이 없는지 확인한다. 
            for(k = 0; k < connection.size(); k++)
                if(friends[i].connection[j] == connection[k]) {
                    break;
                }
            if((k-1) != connection.size())
                connection.push_back(friends[i].connection[j]);
        }</span>
    }
}

진하게 표시한 부분이 문제가 되는데요.
재귀호출을 하게 되면 생각했던대로 친구의 연락망을 찾아내는
함수가 호출되지 않고 자기 자신의 연락망을 찾아내는 함수가 호출되게 됩니다.
재귀호출되는 함수 전후로 주석처리된 부분을 풀어주면 같은 이름이 나오는 것을 보게 됩니다.
무엇이 잘못되었을까요? (소스 전문을 첨부했습니다.)

File attachments: 
첨부파일 크기
Package icon Project.zip16.3 KB
winner의 이미지

문제의 난이도와 coding skill에서 조금 모순을 느낍니다... (^_^)
C++를 작성하는 방식이 꽤 현대적이라는 말입니다.

첨부하신 source와 본문과는 조금 다르더군요.
가장 중요한 문제는 재귀호출의 위치라고 생각되네요.

기존 친구들의 목록을 더한다라는 부분과 친구들의 연락망을 참조해 추가한다를
적절히 통일시킬 수 있도록 해보세요.

그리고 connection은 public으로 하실 거라면 이 경우는 차라리 Student class 밖으로
빠져서 같이 협력하는 구조(그러니까 member 함수의 인자로 넘어가는 방식)이 좋지 않을까 합니다.

댓글 달기

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