Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
4.2k views
in Technique[技术] by (71.8m points)

C++ general question on OOP Design, how to access member of object in the top of hierarchy from bottom

I have a Class A, in the class there is some important member (lets call it someVeryImportantNumber) and also objects of class B. In class B there are objects of class C and so on..., similar to a tree structure (could be 4, 10, or 20 levels of such objects.)

How could i get access to someVeryImportantNumber from the bottom of the hierarchy (to access someVeryImportantNumber from class D).

I was thinking about passing the number down the hierarchy, but this seems not very effective approach when i have lets say 10 or more of levels hierarchy.

Is there some smarter way to do it? I looked at dependency injection but it is not the way to go for me...

Any suggestions? Thank you...

class D {
public:
    void foo() {
        // need to use someVeryImportantNumber here
    }
}

class C {
public:
    D d1;
    D d2;
    D d3;
}

class B {
public:
    C c1;
    C c2;
}

class A {
public:
    int someVeryImportantNumber = 1234;
    B b;
}

int main() {
    A a;
    return 0;
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

You can use a reference to avoid copying that someVeryImportantNumber, and pass it through the constructors:

class D {
    const int& someVeryImportantNumber_;
public:
    D(const int& someVeryImportantNumber) : someVeryImportantNumber_(someVeryImportantNumber) {}
    void foo() {
        // need to use someVeryImportantNumber here
    }
}

class C {
public:
    C(const int& someVeryImportantNumber) 
     : d1(someVeryImportantNumber), d2(someVeryImportantNumber), d3(someVeryImportantNumber) {}
    D d1;
    D d2;
    D d3;
}

class B {
public:
    B(const int& someVeryImportantNumber) 
     : c1(someVeryImportantNumber), c2(someVeryImportantNumber) {}
    C c1;
    C c2;
}

class A {
public:
    A() : b(someVeryImportantNumber) {}
    int someVeryImportantNumber = 1234;
    B b;
}

int main() {
    A a;
    return 0;
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...