Is it possible to give a definition of a class in C++ during allocation, as is allowed in java

后端 未结 4 1681
无人及你
无人及你 2021-01-18 07:03

Or simply put

can I do some thing like

class A {
public:
  virtual void foo() = 0;
};

class B {
  public:
    A *a;
    b(){
       a = new A() { vo         


        
4条回答
  •  被撕碎了的回忆
    2021-01-18 07:59

    No, C++ doesn't have anonymous classes like Java's.

    You can define local classes, like this:

    class B {
      public:
        A *a;
        b(){
           struct my_little_class : public A {
               void foo() {printf("hello");}
           };
           a = new my_little_class();
        }
    };
    

    Or maybe just a nested class:

    class B {
      private:
        struct my_little_class : public A {
            void foo() {printf("hello");}
        };
    
      public:
        A *a;
    
        b(){
           a = new my_little_class();
        }
    };
    

    In C++03, local classes have some limitations (for example, they can't be used as template parameters) that were lifted in C++11.

    In Java, anonymous classes are sometimes used to do what other languages do with anonymous functions like, for example, when you create an anonymous implementation of Runnable. C++11 has anonymous functions (also known as lambdas), so that could be an option if this is what you're trying to achieve.

提交回复
热议问题