C++和go的多态对比

版权声明:本文为博主原创文章,转载时请务必注明本文地址, 禁止用于任何商业用途, 否则会用法律维权。 https://blog.csdn.net/stpeace/article/details/83870996

        C++:

#include <iostream>
#include <typeinfo>
using namespace std;

class Base 
{
public:
	virtual void f() = 0;
};


class D : public Base
{
public:
	int x;
	void f() 
	{
		this->x = 200;
	}
};


int main()
{
	D d;
    d.x = 100;

    Base *pb = &d;
    printf("%s, %d\n", typeid(pb).name(), d.x);

    pb->f();
    printf("%s, %d\n", typeid(pb).name(), d.x);

    // p->x = 1   // no member named 'x' in 'Base'
}

        结果:

P4Base, 100
P4Base, 200

       go:

package main

import (
    "fmt"
)

type BaseIntf interface { 
    f()
}


type D struct {
    x int
}

func (this *D)f()  {
    this.x = 200
}


func main() {
    var d D
    d.x = 100

    var b BaseIntf = &d
    fmt.Printf("%T, %v\n", b, d)
    
    b.f()
    fmt.Printf("%T, %v\n", b, d)

    // b.x = 1   // b.x undefined (type BaseIntf has no field or method x)
}

       结果:

*main.D, {100}
*main.D, {200}

      好好体会一下(注意:类型方面是有区别的)

      不多说。

猜你喜欢

转载自blog.csdn.net/stpeace/article/details/83870996
今日推荐