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
好好体会下,不多说。