2011-08-25 67 views
1

我没有在C++在很长一段时间编程,并且需要一些简单的行为,没有虚拟关键字数量尚未产生:这是C++继承结构吗?

class Base { 
    public: 
    int both() { return a(); } 
}; 

class Derived : public Base { 
    protected: 
    int a(); 
}; 

class Problem : public Derived { 
}; 

Problem* p = new Problem(); 
p.both(); 

,给了我一个编译时错误。这种行为可能与c + +?我是否需要前向声明?一切虚拟关键字?

+2

您应该添加编译时错误。 – Tom

+1

'both'需要公开,但'base'中没有'()'... –

+0

你是来自C#还是Java背景?如果你有不妨阅读一些关于C++的基础知识。 C++的功能与C#或Java相比有所不同。 –

回答

4

不需要。您必须在base中使用纯虚拟a

class Base { 
    virtual int a() = 0; 
    int both() { 
     return a(); 
    } 
}; 
+1

技术上它不一定是纯虚拟的。它只是虚拟的。 OP从未指定他是否希望他的'Base'类是* abstract *基类。您可以轻松地在'Base'类中提供一些默认行为,并使用'viurtal'来覆盖它。 –

3

您的功能both()默认为私有。尝试:

class Base { 
public: 
    int both() { 
     // ... 

(在将来,它会如果你告诉我们什么实际的错误信息是有帮助的。)

4

你应该声明a()功能作为Base纯虚方法类。

class Base { 
    int both() { 
     return a(); 
    } 

    virtual int a()=0; 
}; 

然后实现在Derived

class Derived : public Base { 
    int a(){/*some code here*/} 
}; 

最后,Problem类没有看到both()方法a()方法,自Base私人。做它public

class Base { 
public: 
    int both() { 
     return a(); 
    } 
}; 
+0

+记住要公开。 –

+0

@Michael Krelin - 黑客谢谢,编辑于。 – Tom

2

您需要a()class Base声明,否则编译器不知道该怎么办。

另外,both()目前是一种私有方法(这是类的默认方法),并且应该公开才能从main调用它。

1

你在你的代码中的多个问题:

  • 除非你宣布他们的公共或受保护的,一类的元素是私人作为默认值。
  • 您需要一个虚拟关键字来定义一个虚拟函数,这个虚拟函数可以在父类中调用。
  • new返回一个指向Problem的指针。

下面是根据你的测试一个完整的工作代码:

class Base { 
protected: 
virtual int a()=0; 
public: 
    int both() { 
     return a(); 
    } 
}; 

class Derived : public Base { 
private : 
int a() 
{ 
printf("passing through a!"); 
return 0; 
} 


}; 

class Problem : public Derived { 
}; 

int main(void) 
{ 
    Problem* p = new Problem(); 
    p->both(); 
} 

CodePad测试。

1

正如其他人指出的那样,您需要声明a()为纯虚拟方法Base并将访问权限更改为公开,以使您的代码段正常工作。

这里是C++的另一种方法可能:

template <class D> 
class Base : public D 
{ 
public: 
    int both() { return D::a(); } 
}; 

class Derived : public Base<Derived> 
{ 
public: 
    int a(); 
}; 

我张贴这种方法,因为你在问什么是可能:不是虚函数,你可以通过Curiously recurring template pattern使用静态多态性C++。在实践中,虚拟方法通常是更好的选择,因为它们的灵活性。