C++和go的多态对比 (仔细体会下)

972 篇文章 329 订阅
94 篇文章 44 订阅

        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}

 

      上面两个例子中, 直接通过基类指针/接口访问x都会出现编译错误, 真的没有办法吗? 且看C++程序:

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

class D;

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


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

	D* getD()
	{
		return this;
	}
};


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);

    pb->getD()->x = 300;

    printf("%d\n", d.x);
}

          结果:

P4Base, 100
P4Base, 200
100        

        

           再看go程序:

package main

import (
    "fmt"
)

type BaseIntf interface { 
    f()
    getD() *D
}


type D struct {
    x int
}

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

func (this *D)getD() *D {
    return this
}


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.getD().x = 300
    fmt.Println(d.x)
}

        结果:

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

        

      好好体会下,不多说。

 

  • 2
    点赞
  • 8
    收藏
    觉得还不错? 一键收藏
  • 3
    评论
评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值