可以在分配期间在C ++中给出类的定义,这在Java中是允许的 [英] Is it possible to give a definition of a class in C++ during allocation, as is allowed in java

查看:118
本文介绍了可以在分配期间在C ++中给出类的定义,这在Java中是允许的的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

或者只需输入



即可执行

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

B类{
public:
A * a;
b(){
a = new A(){void foo(){printf(hello);}
}
}

没有,C ++没有类似Java的匿名类。



您可以定义本地类,例如:

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

或者只是一个嵌套类:

  class B {
private:
struct my_little_class:public A {
void foo(){printf(hello);}
};

public:
A * a;

b(){
a = new my_little_class();
}
};

在C ++ 03中,本地类有一些限制(例如,它们不能使用作为模板参数)在C ++ 11中提升。



在Java中,匿名类有时用于做其他语言做匿名函数,当您创建 Runnable 的匿名实现。 C ++ 11有匿名函数(也称为lambdas),所以如果这是你想要实现的,可以是一个选项。


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() { void foo() {printf("hello");}
    }
};

解决方案

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.

这篇关于可以在分配期间在C ++中给出类的定义,这在Java中是允许的的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆