C++ 如何在另一个类中使用变量的值
假设我有一个类,它有一个私有值,例如这个值名是C++ 如何在另一个类中使用变量的值,c++,class,C++,Class,假设我有一个类,它有一个私有值,例如这个值名是a,然后我将它的值设置为10 如何在另一个类中使用其值(10)访问此变量 (我不想使用friend函数和friend类) a、 h main.cpp #include"a.h" int main() { int i=0; int q; a a1; a1.sets(q); cout << s+1 << endl; for (i=1; i<5; i++){ i
a
,然后我将它的值设置为10
如何在另一个类中使用其值(10)访问此变量
(我不想使用friend函数和friend类)
a、 h
main.cpp
#include"a.h"
int main()
{
int i=0;
int q;
a a1;
a1.sets(q);
cout << s+1 << endl;
for (i=1; i<5; i++){
if (s == i) cout << "ok";
}
}
#包括“a.h”
int main()
{
int i=0;
int-q;
a a1;
a1.组(q);
cout如果您不想使用friend
ship,请为此变量添加一个公共接口(setter和/或getter类成员)。要么将变量公开
,要么添加一个函数来获取返回它的值,如int getA()const{return a;}
在类a
中使用私有成员s
而不是全局变量,并通过公共Getter函数get
例如:
#include <iostream>
using namespace std;
class a
{
private:
int s;
public:
void SetS() { cin >> s; }
int GetS() const { return s; }
};
int main()
{
a a1;
a1.SetS();
int s1=a1.GetS();
cout << s1+1 << endl;
for (int i=1; i<5; i++){
if (s1 == i) cout << "ok";
}
}
#包括
使用名称空间std;
甲级
{
私人:
int-s;
公众:
void set(){cin>>s;}
int GetS()常量{return s;}
};
int main()
{
a a1;
a1.集合();
int s1=a1.GetS();
CUT为<代码> A< <代码>做了一个吸气剂函数。在任何处理C++类的书/教程中都可以找到这个问题的答案。请花时间去读一本这样的书。这将比你对这个特定问题的答案更能帮助你。为什么不是Pulic成员<代码> int GET(){返回私有元素};
?不,这不是我的意思,比如说code为什么使用静态全局变量(s
)而不是私有成员?好的,我知道,你只需打印它的值,我想用另一个值添加它,或者以int GetA()的形式使用它const;您只需打印s值,我希望使用此值并将其更改为main它不适合我我也有同样的问题
#include"a.h"
int main()
{
int i=0;
int q;
a a1;
a1.sets(q);
cout << s+1 << endl;
for (i=1; i<5; i++){
if (s == i) cout << "ok";
}
}
#include <iostream>
using namespace std;
class a
{
private:
int s;
public:
void SetS() { cin >> s; }
int GetS() const { return s; }
};
int main()
{
a a1;
a1.SetS();
int s1=a1.GetS();
cout << s1+1 << endl;
for (int i=1; i<5; i++){
if (s1 == i) cout << "ok";
}
}