你能提供一个简单的代码示例吗? (对不起C ++ nube)以及如何从你正在扩展的类中调用一个函数?
答案 0 :(得分:3)
在C ++中,您可以扩展多个类,它被称为多重继承。最有可能这就是你要找的东西。请阅读一本关于多继承和C ++的好书(快速介绍:http://publib.boulder.ibm.com/infocenter/comphelp/v8v101/index.jsp?topic=%2Fcom.ibm.xlcpp8a.doc%2Flanguage%2Fref%2Fcplr134.htm),因为有很多陷阱和细节需要注意。
多重继承的示例:
class A { ... };
class B { ... };
class C: public A, public B {}; // C inherits from A and B.
答案 1 :(得分:3)
一个有用的例子: - )
class CImplementation
{
public:
void doFoo();
};
void CImplementation::doFoo()
{
//implementation
}
class IInterface
{
public:
virtual void foo()=0;
};
class DerivedFromImplementationAndInterface : public CImplementation, public IInterface
{
virtual void foo();
};
void DerivedFromImplementationAndInterface::foo()
{
doFoo();
}
//possible usage:
void method(IInterface& aInterface)
{
aInterface.foo();
}
void test()
{
IInterface* d = new DerivedFromImplementationAndInterface;
method(*d);
}
答案 2 :(得分:2)
C ++没有明确地拥有接口,Java中的接口相当于通常使用只具有纯虚函数的类(加上构造函数,析构函数,复制赋值)来实现:
#include <iostream>
// interface
class Fooable {
public:
virtual int foo() = 0;
virtual ~Fooable() {}
};
// base class
class Base {
public:
void non_virtual_function() { std::cout << "Base::non_virtual_function\n"; }
virtual void virtual_function() { std::cout << "Base::virtual_function\n"; }
};
// derived class, inherits from both Base "class" and Fooable "interface"
class Derived: public Base, public Fooable {
public:
virtual int foo() {
// call base class function
Base::non_virtual_function();
// virtual call to function defined in base class, overridden here
virtual_function();
}
virtual void virtual_function() {
// call base class implementation of virtual function directly (rare)
Base::virtual_function();
std::cout << "Derived::virtual_function\n";
}
void non_virtual_function() {
// not called
std::cout << "Derived::non_virtual_function\n";
}
};
int main() {
Derived d;
d.foo();
}
答案 3 :(得分:1)
不确定你在问什么:
class A
{
public:
void method();
};
class B
{
public:
void method();
};
class C : public A, public B
{
public:
void callingMethod();
};
void C::callingMethod()
{
// Here you can just call A::method() or B::method() directly.
A::method();
B::method();
}
请注意,多重继承会导致真正难以解决的问题,我建议只在必要时使用它。
答案 4 :(得分:1)
如上所述的问题,
C ++是否可以使类扩展一个类并实现另一个类?
没有多大意义。答案就是“是”。您可以从任意数量的类派生:C ++完全支持多重继承。
所以,鉴于所陈述的问题并不真正有意义,至少可能是你意味着要求
C ++是否可以使一个类扩展一个类,从而实现另一个类?
这个问题的答案也是肯定的,但这不是微不足道的。它涉及虚拟继承。这很棘手。
以下是一个例子:
#include <iostream>
void say( char const s[] ) { std::cout << s << std::endl; }
class TalkerInterface
{
public:
virtual void saySomething() const = 0;
};
class TalkerImpl
: public virtual TalkerInterface
{
public:
void saySomething() const
{
say( "TalkerImpl!" );
}
};
class MyAbstractClass
: public virtual TalkerInterface
{
public:
void foo() const { saySomething(); }
};
class MyClass
: public MyAbstractClass
, public TalkerImpl
{};
int main()
{
MyClass().foo();
}
虚拟继承确保TalkerInterface
实例中只有一个类型MyClass
的子对象。这有一些反直觉的后果。一个是“继承在一个实现中”,另一个是该基类子对象的构造发生在每个MyClass
构造函数中,更常见的是在最派生类中。
干杯&amp;第h。,