Rust与C ++的虚函数等效是什么? [英] What is the Rust equivalent to C++'s virtual functions?

查看:358
本文介绍了Rust与C ++的虚函数等效是什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试在Rust中实现类似于类中的C ++虚拟函数的功能,我将拥有一个包含数据的基本结构,然后将一些函数保持未定义状态,例如以下示例:

I'm trying to implement something in Rust that works like a C++ virtual function in a class, I would have a base struct with data, then I would keep some functions undefined, like the following example:

class A {
    int stuff;
public:
    virtual void foo(int a, int b) = 0;
    void function_that_calls_foo() { /*...*/ foo(1, 2); /*...*/ }
}

class B: public A { void foo(int a, int b) { /* ... */ } }

我试图使用函数指针来实现它,但是没有成功.我可以将特征与A的函数一起使用,并在另一个类上实现A,但是我会丢失该结构的数据.在Rust中实现这种事情的最好的(最快的)方法是什么?

I was trying to implement it using function pointers, but without much success. I could use a trait with A's functions, and implement A on the other class, but I would lose the struct's data. What's the best (fastest?) way to implement this kind of thing in Rust?

struct A {
    ...
}

impl A {
    fn function_that_calls_foo(&self) {
        ...
        self.foo(a, b);
        ...
    }
}

struct B {
    a: A;
}

impl B {
    fn xxx(&self) {
        a.function_that_calls_foo(1, 2);
    }

    fn foo(&self, a: i32, b: i32) {...}
}

推荐答案

保留一些未定义的功能

keep some functions undefined

我要添加隐式并且有一些调用该待定义函数的函数".

I'm adding the implicit "and have some functions that call that to-be-defined function".

E_net4说,请使用 特征 :

As E_net4 says, use a trait:

trait Foo {
    fn foo(&self, a: i32, b: i32) -> i32;

    fn function_that_calls_foo(&self) {
        println!("{}", self.foo(1, 2));
    }
}

然后可以实现Base的特征:

struct Base {
    stuff: i32,
}

impl Foo for Base {
    fn foo(&self, a: i32, b: i32) -> i32 {
        self.stuff + a + b
    }
}

Matthieu M.,Rust没有继承,因此请使用组合:

And as Matthieu M. says, Rust doesn't have inheritance, so use composition:

struct Base {
    stuff: i32,
}

impl Base {
    fn reusable(&self) -> i32 {
        self.stuff + 1
    }
}

struct Alpha {
    base: Base,
    modifier: i32,
}

impl Foo for Alpha {
    fn foo(&self, a: i32, b: i32) -> i32 {
        (self.base.reusable() + a + b) * self.modifier
    }
}

通过采用 泛型 ,它受类型参数的约束.

You can combine the two concepts as well, by taking a generic that is constrained by a type parameter.

我将紧随其后 Dietrich Epp点.使用一种新的语言应该涉及检验新的范例.为了代码重用的目的,继承通常不是一个好主意,即使在支持它的语言中也是如此.相反,请创建较小的构建基块并将其组合在一起.

I'll strongly second Dietrich Epp's point. Using a new language should involve checking out new paradigms. Inheritance for the purposes of code reuse is not usually a great idea, even in languages that support it. Instead, create smaller building blocks and combine them together.

这篇关于Rust与C ++的虚函数等效是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆