gpt4 book ai didi

c++ 传递对象的私有(private)变量

转载 作者:行者123 更新时间:2023-12-02 10:13:27 26 4
gpt4 key购买 nike

#include <stdio.h>

class HelloClass
{
float t;
public:
HelloClass(float x) : t(x) {};
float Add(HelloClass a);
};

float HelloClass::Add(HelloClass b)
{
return t + b.t; // How is b.t accessible here?
}

int main()
{
HelloClass a(2), b(3);
printf("hello %f\n", a.Add(b));
return 0;
}
你好,上面的代码编译成功了。但我无法理解 b.t可以访问吗?有人可以对此有所了解吗?

最佳答案

这是预期的行为, private members可以被成员函数访问,即使它们来自其他实例。
(强调我的)

A private member of a class is only accessible to the members andfriends of that class, regardless of whether the members are on thesame or different instances:

class S {
private:
int n; // S::n is private
public:
S() : n(10) {} // this->n is accessible in S::S
S(const S& other) : n(other.n) {} // other.n is accessible in S::S
};

关于c++ 传递对象的私有(private)变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62725841/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com