gpt4 book ai didi

c++ - 我应该怎么做才能访问对象的成员变量?

转载 作者:行者123 更新时间:2023-11-30 02:22:49 25 4
gpt4 key购买 nike

#include<iostream>
using namespace std;
int main(){
class c1{
int i;

public:
int bv;
void seti(int i){
c1::i=i;
}
int geti(){return i;}
int accessbv(c1 inst1);
};
int c1::accessbv (c1 inst1){
cout<<"here in the base accesing inst1's bv"<<inst1.bv;
}

我想访问inst1的成员变量bv。上面的代码编译不通过。我应该怎么办?我还观察到一件事,如果类 c1 的定义是全局的,它就会按照我想要的方式工作。为什么会这样?

最佳答案

仅仅因为类是局部的,并不意味着定义函数的规则会改变。 C++ 标准甚至明确说明了这一点。

[class.local]/2 ,强调我的:

An enclosing function has no special access to members of the local class; it obeys the usual access rules (Clause [class.access]). Member functions of a local class shall be defined within their class definition, if they are defined at all.

上面所说的“规则”只是标准中函数定义相关部分的规定,[dcl.fct.def.general]/2 :

... A function shall be defined only in namespace or class scope.

就是这样。

关于c++ - 我应该怎么做才能访问对象的成员变量?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46873142/

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