C++的虚函数:
纯虚函数说明形式:
virtual 类型 函数名(参数表)= 0 ;
#include <iostream>
using namespace std;
class A
{
protected:
int a;
public:
A(int aa){a=aa;}
virtual void output()
{
cout<<"a="<<a<<endl;
}
};
class B:public A
{
protected:
int b;
public:
B(int aa,int bb):A(aa)
{
b=bb;
}
virtual void output()
{
cout<<"b="<<b<<endl;
}
};
int main()
{
A a(5);
B b(15,25);
A* p;
p=&b;
p->output(); //b=25
return 0;
}
多态性:
1、多态性(Polymorphism)是指一个名字,多种语义;或界面相同,多种实现。
2、重载函数是多态性的一种简单形式。
3、虚函数允许函数调用与函数体的联系在运行时才进行,称为动态联编。
抽象:
虚函数即为一个抽象函数。
所谓的抽象类即指含有至少一个抽象函数的类。抽象类不能被实例化,抽象函数一旦被实例化,则会产生报错 “can not declare variable xx to be abstract type xx”。
抽象类实际上是提供了一个接口,以便于用户在使用的时候可以不必关心功能是如何实现的,只需要关心有什么功能。
简单的rpc客户端和服务器端的实现
客户端调用服务器端的程序计算矩形的面积
客户端:
package main
import (
"fmt"
"net/rpc"
"os"
)
type Rectangle struct {
L, W int
}
type Aera int
func main() {
pClient, err := rpc.Dial("tcp", "127.0.0.1:7777")
if err != nil {
fmt.Fprintf(os.Stderr, "err : %s\n", err.Error())
return
}
defer pClient.Close()
// 同步RPC
var area int
err = pClient.Call("Area.Mult", &Rectangle{2, 7}, &area)
if err != nil {
fmt.Fprintf(os.Stderr, "err : %s\n", err.Error())
return
}
fmt.Fprintf(os.Stdout, "the rectangle's area = %d\n", area)
}
服务器端:
package main
import (
"fmt"
"net"
"net/rpc"
"os"
)
type Rectangle struct {
L, W int
}
type Area int
func (this *Area) Mult(rectangle *Rectangle, area *int) error {
*area = rectangle.L * rectangle.W
return nil
}
func main() {
a := new(Area)
server := rpc.NewServer()
server.Register(a)
listener, err := net.Listen("tcp", ":7777")
defer listener.Close()
if err != nil {
fmt.Fprintf(os.Stderr, "error %s\n", err.Error())
return
}
server.Accept(listener)
}