具有常量构造函数参数的 C++ 变量构造函数方法

标签 c++ class constructor function-pointers

我正在尝试在类构造函数中使用函数指针,以便我可以选择使用哪个函数来构造类的对象。我想这样做是为了能够改变类中的成员变量是如何用一组相同的构造函数参数确定的方法。我已经能够成功编写此代码,如以下代码所示,但是我需要声明所有指向友元的单独函数。

我的问题:有没有办法将名称未知的函数(即只有返回类型和一组参数已知)声明为友元?我想要这个是因为在未来的开发中可能会添加新的功能,而类保持不变,我不想为每个新功能添加新的友元声明。

当然,我也愿意接受其他方法来实现我的目标。

#include <iostream>

class foo
{
private:
    int var_1;
public:
    foo(void (*functionPtr)(foo*))
    {
        functionPtr(this);
    }
    ~foo(){}

    int get_var() {return var_1;}

    friend void function_1(foo*); // declare all unique
    friend void function_2(foo*); // functions as friends

    /*friend void (*functionPtr)(foo*); // this is what I want:
                                        // to declare all functions with
                                        // a specific return type and
                                        // specific arguments as a friend
                                        // of this class */
};

void function_1(foo* T)
{
    std::cout << "function 1" << std::endl;
    T->var_1 = 1;
}

void function_2(foo* T)
{
    std::cout << "function 2" << std::endl;
    T->var_1 = 2;
}

int main()
{
    foo F1(&function_1);
    std::cout << F1.get_var() << std::endl;

    foo F2(&function_2);
    std::cout << F2.get_var() << std::endl;

    return 0;
}

最佳答案

你可以将你想要初始化的部分移动到一个单独的地方,在那里它们被认为是公共(public)的:

struct foovars
{
    int var_1;
};

class foo : foovars
{
public:
    foo(void (*functionPtr)(foovars*))
    {
        functionPtr(this);
    }
};

void function_1(foovars* T)
{
    std::cout << "function 1" << std::endl;
    T->var_1 = 1;
}

从持有 class foo 实例的代码的角度来看,现在您的成员变量和以前一样私有(private)。但是设法接收 foovars* 的特殊函数可以修改其成员。

关于具有常量构造函数参数的 C++ 变量构造函数方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37162688/

相关文章:

c++ - 如何使用 char 数组字母表使用仿射密码对文本进行编码?

c++ - 使用 crtp 初始化引用成员

c++ - 如何获取pam_ldap中当前的PAM用户?

html - 如何将此表格和按钮放在图像旁边(图像右侧)

c++ - C++中的自动构造函数生成?

c++ - 关于编译时 1.constructor 和 2.array 定义的一些疑问

c++ - 检查类型是否具有在 C++ 中定义的 [][]

java - 检查类是否存在于 Java 类路径中而不运行其静态初始化程序?

C++ 无法创建用户定义类的 vector

c++ - 用大括号调用构造函数