【问题标题】:Use an external function as a method of a class使用外部函数作为类的方法
【发布时间】:2021-07-12 08:25:57
【问题描述】:

我正在尝试使这段代码工作:

#include <iostream>
using namespace std;


int f(int x) {
    return x+1;
}

class A {
    public:
    int g(int y);
};

int A::g(int y) = f;


int main() {
    A test;
    cout << test.g(3) << endl;
    return 0;
}

由于int A::g(int y) = f; 行,它无法编译。 实现外部函数可以用作方法的正确方法是什么?

【问题讨论】:

  • int A::g(int y) { return f(); }。这不是问题要问的,但非成员函数和成员函数是不可互换的。

标签: c++ class methods


【解决方案1】:

您可以使用指针作为A 类的成员。现在将函数f 分配给gA 成员。

int f(int x) {
    return x+1;
}

class A {
    public:
    int (*g)(int);
};

int main(){
    A test;
    test.g = f;
    cout << test.g(10); // prints 11
}

【讨论】:

  • 这比直接实现效率低吗?根据我对 C++ 的理解,使用标志编译时有任何区别,但我想确定
【解决方案2】:

您可以通过实现() 运算符使您的函数成为可调用对象来实现同样的目的。所以你可以把它作为类的成员,然后它通常可以用作类对象的函数。

#include <iostream>

struct do_something{
    int operator()(int num){
        return num;
    }
};
class test{
    int sum;
    public:
        do_something fun;
};

int main(){
    test obj;
    std::cout << obj.fun(10);
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-05-10
    • 2015-10-04
    • 2021-11-21
    • 2013-04-02
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多