相关疑难解决方法(0)

构造函数的C++虚函数

为什么以下示例打印"0"以及必须更改它以打印"1",如我所料?

#include <iostream>
struct base {
   virtual const int value() const {
      return 0;
   }
   base() {
      std::cout << value() << std::endl;
   }
   virtual ~base() {}
};

struct derived : public base {
   virtual const int value() const {
      return 1;
   }
};

int main(void) {
   derived example;
}
Run Code Online (Sandbox Code Playgroud)

c++ oop virtual constructor class

57
推荐指数
3
解决办法
4万
查看次数

从构造函数调用方法

请原谅任何小的语法错误或诸如此类的错误,我正在通过Jitsi模块遇到这个问题并且不熟悉Java,想要确认发生了什么以及为什么以及如何修复它.

 public abstract class A
{
  public A()
  {
    this.load();
  }

  protected void load()
  {

  }
}

public class B extends A
{
  private String testString = null; 

  public B()
  {
    super();
  }

  @Override
  protected void load()
  {
    testString = "test";
  }
}
Run Code Online (Sandbox Code Playgroud)

应用程序在使用按名称加载类方法创建类B的实例时执行此操作:

  • 在B类中调用重写的load()
  • 初始化变量(根据调试器调用"private string testString = null"),将它们清零.

这是预期的Java行为吗?什么可能导致这个?它是在1.7 JDK上运行的Java 1.6应用程序.

java constructor class

22
推荐指数
2
解决办法
2万
查看次数

构造函数中的多态方法(Java)

类在构造函数中A调用public方法f().B类f()使用自己的实现覆盖方法.

假设你intantiate对象B..方法f()对象B将在对象的构造函数被调用A,虽然对象B未完全初始化.

谁能解释这种行为?

编辑:是的,它不推荐练习..但我不明白为什么 Java不调用f()基类的实现A而不是"伸出"到f()派生类的实现B.

码:

class A {
    A() {
        System.out.println("A: constructor");
        f();
    }

    public void f() {
        System.out.println("A: f()");
    }
}

class B extends A {
    int x = 10;
    B() {
        System.out.println("B: constructor");
    }

    @Override
    public void f() {
        System.out.println("B: f()");
        this.x++;
        System.out.println("B: x = " + x);

    }
}

public …
Run Code Online (Sandbox Code Playgroud)

java polymorphism inheritance constructor overriding

11
推荐指数
2
解决办法
3733
查看次数

标签 统计

constructor ×3

class ×2

java ×2

c++ ×1

inheritance ×1

oop ×1

overriding ×1

polymorphism ×1

virtual ×1