我来自node.js,我想知道是否有方法在C++中执行此操作。这将是C++相当于:初始化后更改变量类型C++
var string = "hello";
string = return_int(string); //function returns an integer
// at this point the variable string is an integer
所以在C++我想要做的有点像这样的东西......
int return_int(std::string string){
//do stuff here
return 7; //return some int
}
int main(){
std::string string{"hello"};
string = return_int(string); //an easy and performant way to make this happen?
}
我用JSON的工作,我需要列举一些字符串。我意识到我可以将return_int()
的返回值赋给另一个变量,但我想知道是否有可能为了学习和可读性而将字符串类型的变量重新分配给int。
不,这不是可能的(至少不是以“简单高效的方式来实现这一目标?”)。 C++在编译时修复任何变量类型。 –
请参阅http://stackoverflow.com/questions/1517582/what-is-the-difference-between-statically-typed-and-dynamically-typed-languages –
请记住,语言静态化并不相同键入为强类型。例如: JavaScript是动态和弱的,它允许隐式类型转换(如x =“3”+ 5)。 Python是动态和强烈的,它允许显式类型转换(x =“3”+“5”或x = 3 + 5,但不混合)。 C++是静态的,如前所述,因为它不是预期的行为(您必须在编译时显式声明x的类型),所以不是一种简单的方法 –