有没有什么方法可以使用一个函数中定义的常量变量,也可以由c++中同一程序中的其他函数使用

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++

本文关键字:函数 也可以 其他 程序 变量 c++ 定义 可以使 方法 什么 有没有      更新时间:2023-10-16

我们如何使用在一个函数中定义的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作为成员变量,并使sample成为class(如果它当前是namespace(?

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

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

有两种已知的方法。

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

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:
...
}
我终于得到了答案。

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

示例:in.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());
}
相关文章: