C++:如何在同一类的不同函数中定义元素

C++: how to get element defined in a different function of same class?

本文关键字:一类 函数 元素 定义 C++      更新时间:2023-10-16

我在头文件中定义了一个类,如下所示:

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);

这完全取决于testtraincount的用途......