重载函数中的静态变量 [英] Static Variables in Overloaded Functions

查看:225
本文介绍了重载函数中的静态变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个函数执行以下操作:


  • 当函数被调用并传递一个真正的布尔值时,它会设置一个静态bool值为true

  • 当函数被调用并传递一个字符串时,如果静态bool值设置为true,它将对该字符串执行一些操作



这是我的担心 - 两个重载函数之间的静态变量是否保持不变?如果没有,我可以简单地创建一个单独的函数来设计用于跟踪bool值,但我会尽量保持简单。 解决方案

p>不,它创建两个独立的静态变量 - 每个函数都有一个。任何C ++函数的名称都由它的明显名称和它的参数类型组成,并且静态名称(概念上至少)被添加到该名称中。与其添加另一个函数,您可以考虑对包含函数的类使用静态变量,尽管这不会给您完全相同的行为,或者将其放置在匿名名称空间中:

  namespace {
int myvar = 0;
}

int f(bool b){
return myvar;
}

int f(常量字符串& s){
return myvar;

$ / code>

制作一个类的函数成员:

  // ah 
class A {
public:
static int f(bool b){
return MYVAR;
}

static int f(const string& s){
return myvar;
}
private:
static int myvar;
};

// a.cpp
int A :: myvar = 0;

// main.cpp

#include< iostream>
#include< a.h>
int main(){
std :: cout<< A :: f(false)<< A :: f(string(foobar))<<<的std :: ENDL;
}


I have a function which does the following:

  • When the function is called and passed a true bool value, it sets a static bool value to true
  • When the function is called and passed a string, if the static bool value is set to true, it will do something with that string

Here is my concern -- will a static variable remain the same between two overloaded functions? If not, I can simply create a separate function designed to keep track of the bool value, but I try to keep things simple.

解决方案

No, it creates two separate static variables - one for each function. The name of any C++ function is made op of its apparent name and its parameter types, and the name of the static is (conceptually at least) tacked on to that. Rather than add yet another function, you could consider making the variable static with respect to the class containing the functions, although this does not give you exactly the same behaviour, or place it in an anonymous namespace:

namespace {
   int myvar = 0;
}

int f( bool b ) {
   return myvar;
}

int f( const string &  s  ) {
   return myvar;
}

To make the functions members of a class:

// a.h
class A {
   public:
    static int f( bool b ) {
       return myvar;
    }

    static int f( const string &  s  ) {
       return myvar;
    }
  private:
     static int myvar;
};

// a.cpp
int A::myvar = 0;   

// main.cpp

#include <iostream>
#include <a.h>
int main() {
    std::cout << A::f(false) << A::f( string("foobar") ) << std::endl;   
}

这篇关于重载函数中的静态变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆