search

Home  >  Q&A  >  body text

c++ - 如何设计将一个类放在另一个类名下

有两个类foo和bar,bar为foo服务
我希望设计成
foo 与 foo::bar , 而不是 foo 与 bar

类似
std::vector<int>::iterator 和 std::vector

应该怎样把bar的class放在foo里面?

迷茫迷茫2808 days ago353

reply all(2)I'll reply

  • 巴扎黑

    巴扎黑2017-04-17 13:28:19

    You can use class nesting or typedef. The vector::iterator you mentioned is a type alias defined by typedef

    class Out {
    public:
        class Inside {
        
        };
    };
    
    Out some1;
    Out::Inside some2;
    class A {
    
    };
    
    class B {
    public:
        typedef A Inside;
    };
    
    A some1;
    B some2;
    B::Inside some3;

    reply
    0
  • 天蓬老师

    天蓬老师2017-04-17 13:28:19

    C++ supports nested classes, such as

    class foo {
        class bar { /* ... */ };
        /* ... */
    };

    or

    class foo {
        class bar;
        /* ... */
    };
    
    class foo::bar {
        /* ... */
    };

    For specific usage, please refer to C++ Primer 5ed. section 19.5 Nested Classes.

    In addition, std::vector<int>::iterator is an alias of another class in std::vector (typedef), not a nested class of std::vector.

    reply
    0
  • Cancelreply