是否有帮助使用私有结构的功能

Is there a function that help using a private struct

我需要一个可以进入私有结构的函数

    #include <iostream>
    using namespace std;

    struct abc {
    private:
        int a;
    }b;

    int main(){
        //i want to use the variable a
        system("pause");
    }

如果要允许特定的 class/struct 或函数访问私有成员,请使用 friend 声明。这通常仅用于密切相关的事物,以免使其他地方的所有事物都可以访问成员(在其他语言中,类似 internal 的事物)。

struct abc {
private:
    int a;
    friend int main();
};

void foo(abc &x) {
    x.a = 5; // ERROR
}
int main(){
    abc x;
    x.a = 2; // OK
    foo(x);
    //i want to use the variable a
    system("pause");
}

如果您想要只读访问,通常会使用 "getter",例如

struct abc {
    int get_a()const { return a; }
private:
    int a = 45;
};

int main() {
    abc x;
    std::cout << x.get_a(); // OK
}

以及用于读写的get 和set 函数。 set 函数可能会进行额外的验证或其他逻辑。

struct abc {
    int get_a()const { return a; }
    void set_a(int x)
    {
        if (x % 2) throw std::invalid_argument("abc must be even");
        a = x;
    }
private:
    int a = 45;
};

int main() {
    abc x;
    x.set_a(50);
    std::cout << x.get_a();
    x.set_a(51); // throws
}

这会破坏封装。

如果你需要读取变量 a 你创建一个 getter:

struct abc {
int getA() const;
private:
    int a;
};

如果您需要修改变量,您应该创建一个 setter:

struct abc {
void setA(int);
private:
    int a;
};

有一种方法可以使用 friend function,但我不建议您这样做。

如果它是 struct 如果您需要访问且不需要封装,请考虑制作 a public。

除了声明它们的 class 之外,任何人都不应访问私有字段和方法。但是,在某些情况下需要它。例如,如果你想 serialize/print 你的结构。对于这些情况,您可以使用 friend 关键字声明一个函数或另一个 class。例如:

struct abc
{
private:
    friend std::ostream &operator<<(std::ostream &stream, const abc &s);

    int a;
};

然后您将在某处实现具有相同签名 std::ostream &operator<<(std::ostream &stream, const abc &s); 的函数,并且它可以访问 abc::a:

std::ostream &operator<<(std::ostream &stream, const abc &s)
{
    return stream << s.a;
}

这将允许使用您的结构,例如 std::cout

请注意,像这样的真实案例并不多,您应该尽可能避免使用 friend。在这种情况下,例如 getter 方法会做同样的事情,并且您可以在不破坏封装的情况下避免整个问题。