Warning: file_get_contents(/data/phpspider/zhask/data//catemap/6/cplusplus/130.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C++ CppUnit:为什么静态局部变量保持其值?_C++_Oop_Static_Initialization_Cppunit - Fatal编程技术网

C++ CppUnit:为什么静态局部变量保持其值?

C++ CppUnit:为什么静态局部变量保持其值?,c++,oop,static,initialization,cppunit,C++,Oop,Static,Initialization,Cppunit,我试图使用CppUnit测试一个方法,该方法应该只在第一次调用时执行一些代码 class CElementParseInputTests: public CppUnit::TestFixture { private: CElement* element; public: void setUp() { element = new CElement(); } void tearDown() { delete element;

我试图使用CppUnit测试一个方法,该方法应该只在第一次调用时执行一些代码

class CElementParseInputTests: public CppUnit::TestFixture {
private:
    CElement* element;
public:

    void setUp() {
        element = new CElement();
    }

    void tearDown() {
        delete element;
    }

    void test1() {
        unsigned int parsePosition = 0;
        CPPUNIT_ASSERT_EQUAL(false, element->parseInput("fäil", parsePosition));
    }

    void test2() {
        unsigned int parsePosition = 0;
        CPPUNIT_ASSERT_EQUAL(false, element->parseInput("pass", parsePosition));
    }
我要测试的递归方法:

bool CElement::parseInput(const std::string& input, unsigned int& parsePosition) {
    static bool checkedForNonASCII = false;
    if(!checkedForNonASCII) {
        std::cout << "this should be printed once for every test case" << std::endl;
        [...]
        checkedForNonASCII = true;
    }
    [...]
    parseInput(input, parsePosition+1)
    [...]
}
bool CElement::parseInput(const std::string&input,unsigned int&parsePosition){
静态bool checkedForNonASCII=假;
如果(!checkedForNonASCII){
这就是我们应该做的

使用说明符static在块作用域中声明的变量具有静态存储持续时间,但在控件第一次通过其声明时初始化(除非其初始化为零或常量初始化,可在首次输入块之前执行)。在所有后续调用中,将跳过声明


这意味着第一次调用时,
checkedForNonASCII
将仅初始化为
false
一次。对于进一步调用,将跳过初始化;即,
checkedForNonASCII
不会再次初始化为
false

另一个答案所说的。但这可能是您真正想要的:

bool CElement::parseInput(const std::string& input, unsigned int& parsePosition)
{
    [...] // your code for validating ascii only characters goes here
    if (hasNonAsciiCharacters) {
       return false;
    }

    return parseInputInteral(input, parsePosition);
}

bool CElement::parseInputInternal(const std::string& input, unsigned int& parsePosition)
{
    [...]
    parseInputInternal(input, parsePosition+1);
    [...]
    return result;
}

不会为每个测试用例重新创建和销毁对象。只有在未指定
static
时才会发生这种情况。在任何情况下,(1)静态bool
不是对象的一部分,以及(2)即使是,也不会为每个对象重新创建它。它是静态的。它保留其值。这就是
static
的意思。如果您希望在每次创建对象时初始化一个变量,它应该是一个在构造函数中初始化的非静态成员。此外,如果您有一个递归函数在“first”中执行特殊操作调用时,一个常见的模式是使用一个非递归包装器来完成特殊的工作,然后调用一个私有递归函数来完成真正的工作(并且可以假设特殊的工作已经完成)。