【问题标题】:Is there any way we can use a const variable defined in one function can be used by other function in the same program in c++有什么方法可以使用在一个函数中定义的 const 变量可以被 C++ 中同一程序中的其他函数使用
【发布时间】:2020-07-14 13:56:58
【问题描述】:

我们如何使用在一个函数中定义的 const std::string 变量在同一程序的另一个函数中使用。

int sample::convert()
{
    fun()
     {
        //returns string;
     }
    const std::string sender = fun()
}

void sample::write()
{
   //I want to use sender variable here like below
   std::string var;
   var = sender;

}

【问题讨论】:

  • 问题是sender 变量是一个临时变量。您不能在 convert() 函数之外使用它。
  • @vahancho:如果它具有static 存储持续时间,您也无法访问它(以便携式方式)。
  • 还要注意senderconst 并不相关——它仍然只是一个局部变量。每次调用sample::convert,都会创建一个新的sender
  • 您所要求的,确切地说,是无法完成的。当函数返回时,在一个函数中定义的正常变量将不再存在。有几件事做类似的事情,但我们需要知道你的目的是什么,为什么要这样做。

标签: c++


【解决方案1】:

不,那是不可能的。

为什么不将sender 作为成员变量并将sample 设为class,如果它当前是namespace

【讨论】:

  • 是的,目前是它的命名空间。但是发件人正在使用 fun() 的返回。我已经编辑了我的问题。
【解决方案2】:

如果实际问题是你不知道如何定义常量成员变量,那就像你在函数本身中定义一样:

class sample
{
    const std::string sender = "sample";
    // Other members...
};

【讨论】:

  • 为什么不将其设为静态成员以在没有实例的情况下启用访问?我认为这将更接近 OP 想要的
【解决方案3】:

有两种已知的方法。

首先,返回字符串以在某处使用它(它可能不是您想要的,但它会起作用)。

std::string sample::convert()
{
    const std::string sender = "sample"
    return sender;
}

void sample::write()
{
   //I want to use sender variable here like below
   std::string var;
   var = sender();
}

或者,最好将此变量声明为类成员变量:

class sample {
    std::string sender = "sample"; // if not it's going to be modified, then use 'const'
public:
    ...
}

【讨论】:

    【解决方案4】:

    我终于得到了答案。

    我们需要在全局范围内声明一个 char *。然后使用 const_cast 我们可以将常量字符串转换为 char 并赋值。

    示例: 在 .h 文件中:

    char * abc;
    

    在 .cc 文件中:

    func()
        {
         const std::string cde = "Hello";
         //now to use this constant string in another function,we use const cast and 
         //assign it to abc like below
         abc = const_cast <char *>(cde.c_str());
        }
    

    【讨论】:

    • 这是您的other bad answer 的重复。这并不像你认为的那样。当函数返回时,字符串变量cde 将被销毁。然后指针abc 悬而未决。这段代码完全被破坏了。
    • 赞成这个明显错误答案的人正在使 Stack Overflow 变得更糟。恭喜,我猜...
    猜你喜欢
    • 2017-06-09
    • 1970-01-01
    • 2019-01-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多