是否有一个帮助使用私有结构的函数

问题描述 投票:1回答:3

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

    #include <iostream>
    using namespace std;

    struct abc {
    private:
        int a;
    }b;

    int main(){
        //i want to use the variable a
        system("pause");
    }
c++ struct private
3个回答
4
投票

这将打破封装。

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

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

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

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

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

如果是struct,请考虑将a公开,如果您需要访问且没有封装。


1
投票

如果要允许特定的类/结构或函数访问私有成员,请使用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
}

0
投票

除了声明它们的类之外,任何人都不应该访问私有字段和方法。但是,有些情况需要它。例如,如果您想序列化/打印结构。对于这些情况,您可以使用friend关键字声明函数或其他类。例如:

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方法可以做同样的事情,你可以在不破坏封装的情况下避免整个问题。

© www.soinside.com 2019 - 2024. All rights reserved.