3

我有一个超类,其中定义了一个类。像:

class A {
 public:
  class B {public: bool value;};

  A() {
      DoStuff(b_);
  }
  B b_;
 private:
  virtual void DoStuffImpl(B& b) = 0;
  void DoStuff(B& b) { return DoStuffImpl(b); }
};

class X : public A {
  // ...
 private:
  virtual void DoStuffImpl(B& b);
  void UseBForSomethingElse(B& b);
};

void X::DoStuffImpl(B& b) {
    UseBForSomethingElse(b);
}

void X::UseBForSomethingElse(B& b) {
    b.value = true;
}

int main(){
    X x;
    return x.b_.value;
}

我的编译器似乎理解DoStuffImpl()得很好。但是,当我添加 时UseBForSomethingElse(),编译器找不到B该类的定义。我试图通过做进一步指定bool UseBForSomethingElse(A::B& b)。这已编译,但在链接期间失败。

如何正确指定 parent B,为什么它适用于虚拟功能而不适用于另一个?

4

2 回答 2

1

基于 OP 编辑​​的编辑:

ideone 说您有运行时错误的原因是因为您从 main 返回 1。任何非零返回值main都将被视为执行失败。如果你只是改变返回return !x.b_.value;ideone 按预期报告成功。

Original answer:

void UseBForSomethingElse(const B& b) {
    b.value = true;
}

You can't assign into a constant reference (b), so that's certainly one of your problems.

Also, you didn't qualify the definition of UseBForSomethingElse with X:: so the compiler doesn't put it in the scope of X, preventing it from seeing the parent's nested class.

于 2012-11-09T17:00:27.803 回答
1

Your updated post doesn't properly qualify UseBForSomethingElse().

void UseBForSomethingElse(const B& b)

should be

void X::UseBForSomethingElse(const B& b)

Once this is fixed, you still have a problem (and heaven help me if I get this wrong).

You're firing a virtual method from a base class constructor without the derived class finishing construction. I.e, UseBForSomethingElse (non-virtual) is fired from DoStuffImpl() (virtual, pure @ A, defined in X) before X is finished base-construction (you're, in fact in X's base-construction when you make the call). This will trigger a 'pure virtual function called' since X's vtable isn't fixed up until its constructor is actually entered.

This does happen on my machine as well, btw.

于 2012-11-09T17:06:42.633 回答