C++:如何在同一类的不同函数中定义元素
C++: how to get element defined in a different function of same class?
我在头文件中定义了一个类,如下所示:
class myClass
{
public:
void test();
void train();
private:
bool check;
}
然后在 cpp 文件中,我这样做了:
void myClass::test()
{
int count = 9;
//some other work
}
void myClass::train()
{
int newValue = count;
....
}
然后毫不意外地,我收到一个错误,说计数未定义。所以我想做的是在我的train
函数中使用test
中定义的计数值。有什么好方法可以在不使用任何其他依赖项的情况下做到这一点吗?谢谢。
嗯,
是的。这称为成员变量。就像你的bool check;
一样.
做
private:
bool check;
int count;
然后直接在函数中使用它。
void myClass::test()
{
count = 9;
//Same as this->count = 9;
}
void myClass::train()
{
int newValue = count;
//Same as int newValue = this->count;
}
在您的示例中,当方法测试完成其工作时,count
变量不再存在,因此无法访问它。您必须确保其生命周期足够长,可以从另一个地方访问。使其成为类字段可以解决问题(这就是类字段的:))。
这样做:
class myClass
{
public:
void test();
void train();
private:
bool check;
int count; // <- here
}
然后
void myClass::test()
{
count = 9;
//some other work
}
但这不是唯一的解决方案。你可以用另一种方式来做,比如:
class myClass
{
public:
int test()
{
// do some work
return 9;
}
void train(int count)
{
int newValue = count;
}
}
// (somewhere)
myClass c;
int count = c.test();
c.train(count);
这完全取决于test
、train
和count
的用途......
相关文章:
- 获取从C++中同一类中的构造函数调用的方法返回的值
- 如何封装一个函数,以便它只能由同一类中的一个其他函数调用?
- 如何使用connect将qml按钮与同一类的cpp函数连接起来
- 类成员函数无法访问同一类的私有结构节点?
- 无法将指向类的成员函数的函数指针作为参数传递给同一类的另一个成员函数
- 在 c++ 中将对象设置为等于同一类的构造函数是否有效?
- 如何将一个类的成员函数用作另一类的友元函数
- 如何获取同一类函数中类成员的函数指针?
- 一类嵌套类不能用作模板函数类型名
- 在多个文件中与同一类分开函数
- 将1D或2D向量传递给同一类的构造函数
- 仅一个功能的链接错误.在同一类和CPP文件中具有相似签名的其他函数工作正常
- 让构造函数在其初始化列表中调用同一类的另一个构造函数是否有效
- 如何将两个类成员函数与同一类中的另一个函数一起添加
- 在C++中,类是否可以包含指向构造函数中初始化的同一类的指针?
- C 使用来自另一类的函数
- 如何为同一类对象的成员函数保留单独的变量副本?
- 如何将成员函数用于同一类的不同对象
- 为什么一个非平凡的成员需要为同一类中的匿名联合定义构造函数
- 我无法使用类变量作为同一类函数的默认参数