如何解决抽象函数在C ++中为纯虚函数是否可以防止该类的实例化,并且它们是定义合同的方式吗?
我认为您不能使用抽象函数实例化一个类,但我不确定。
此外,抽象函数是定义合同的一种方式,对吗?由于必须在子类中实现它们,因此就像合同一样。
此外,我还想知道抽象函数是否只能有一个实现或多个实现,以及它们是否可以存在于非抽象类中。一世 我不认为它们可以存在于非抽象类中,因为抽象函数意味着一个类是抽象的,并且我相信抽象函数可以具有多个实现。
解决方法
我认为您不能使用抽象函数实例化一个类,但我不确定。
不,你不能。
此外,我还想知道抽象函数是否只能具有一个实现或多个实现,并且它们是否可以存在于非抽象类中。
这就是他们的全部目的。它们可以(静默地)出现在具有抽象基础的类层次结构中,从而使派生类也变得抽象。但是最后,它们必须必须在应该可实例化的派生类中实现。
我不认为它们可以存在于非抽象类中,因为抽象函数意味着一个类是抽象的,并且我相信抽象函数可以具有多个实现。
一个纯虚函数(无论是继承还是直接声明) 是使类抽象的原因。
您提到的合同:
可以将纯虚拟功能视为合同。
在c ++中,它们通常用于声明如下的接口
struct IMyInterface {
virtual void foo(int a,std::string b) = 0;
virtual int bar() = 0;
virtual ~IMyInterface() {}; // Note: Interfaces must have at least a
// virtual destructor function defined,but
// no other non pure virtual funcitons must
// be implemented.
};
一个类可以继承多个接口,而其他类则可以将它们用作协定,而无需知道实现该接口的具体类。
// A class implementing the interface
class Baz : public IMyInterface {
virtual void foo(int a,std::string b) {
// Do something with a and b
// ...
}
virtual int bar() {
return 3 * 5;
}
virtual ~Baz() = default; // Default destructors aren't automatically virtual!
};
// Another class implementing the interface
class Twiddle : public IMyInterface {
virtual void foo(int a,std::string b) {
// Do something with a and b
// ...
}
virtual int bar() {
return 42;
}
virtual ~Twiddle() = default;
};
// A class using the interface
class Client {
public:
// The concrete implementation can be configured by passing
// the interface in the vonstructor
Client(IMyInterface* intf_) : intf(intf_) {}
void someMethod() {
intf->foo(42,"Hello universe!");
int x = intf->bar();
}
private:
IMyInterface* intf;
};
另一种方法是在Template Method设计中使用它们。即一个抽象类,它实现了算法或某些行为,并且依靠继承类来实现它的基本部分。
class MyAbstractBase {
protected:
struct context {
int paramA;
std::string paramB;
};
int operateOnContext(const context& ctx) = 0;
public:
// Some behavior exposed to client classes
int doSomething() {
// Setup a context
context ctx { 42,"Hello universe!" };
return operateOnConetxt(ctx);
}
virtual ~MyAbstractBase() = default;
};
// An inherited class,which will write the context to a file
class Derived1 : public MyAbstractBase {
protected:
int operateOnContext(const MyAbstractBase::context& ctx) {
std::ofstream out("AFile.txt");
out << "Param A is:" << ctx.paramA << std::endl;
out << "Param B is:" << ctx.paramB << std::endl;
}
public:
virtual ~Derived1() = default;
};
// Another inherited class,which will send the context over a network connection
class Derived2 : public MyAbstractBase {
protected:
int operateOnContext(const MyAbstractBase::context& ctx) {
NetworkConn conn;
conn.connect("NetworkEndpoint");
conn.send(ctx.paramA);
conn.send(ctx.paramB);
conn.disconnect();
}
public:
virtual ~Derived2() = default;
};
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。