gpt4 book ai didi

c++ - 错误 : Variable Not declared in this scope

转载 作者:行者123 更新时间:2023-11-30 05:17:32 26 4
gpt4 key购买 nike

在用于测试的主文件中,我从类似于此的代码开始。

 //Initialize the data type for the vectors and input variables
if ( choice == 1 )
{
vector<int>MyVector{};
vector<int>NewVect{};
int k1{}, k2{};
}

else if ( choice == 2 )
{
vector<float>MyVector{};
vector<float>NewVect{};
float k1{}, k2{};
}
//Exact Same block for double
while ( true )
{
cout<<": ";
cin>>k1>>k2;
if ((k1 == 0 ) && (k2 == 0)) break;
else
{
MyVector.push_back(k1);
MyVector.push_back(k2);
continue;
}
}
//Insert Sort Algorithm test, Imported from class InsertSort.
//NewVector = sort.sort(MyVector)
return 0;
}

它继续像这样进入另外两个分别声明 float 和 double 的 else if 语句(使用相同的变量名)。然而,编译停止并表示 k1、k2、MyVector 和 NewVector 未在此范围内进一步声明到程序中。我在 main 的“全局”部分声明了它,所以我不太理解为什么声明没有发生。在 if/else if 语句中尝试声明不同类型的相同变量是不可能的吗?

我正在尝试这样做以避免在输入循环中进行额外的测试,这样就可以检查数据类型,定义正确的数据类型并且代码会比原来更短。知道发生了什么吗?

编辑:添加代码。

最佳答案

您不能声明类型取决于运行时条件的变量。变量类型在编译时声明/指定。知道这一点后,您尝试在 if block 内声明不同的类型,但随后每个变量的范围仅限于声明它的 block 。

您正在尝试的可以使用某种多态变量任何类型的变量来实现,C++17 但不是之前,在 std::any 的名称下。同时,您可以尝试使用 unions 为自己制作类似的东西。下面可以提供一个开始示例来创建您自己的 any 类型,该示例定义了一个包含 intany:

#include <iostream>
#include <vector>

struct any {
union { int intVal = 0; double dblVal;};
enum {Int = 1, Dbl = 2} type = Int;

any(int val) : intVal(val) {type = Int;}
any(double val) : dblVal(val) {type = Dbl;}
any() {}
};

std::ostream& operator <<(std::ostream& os, const any& x) {
switch(x.type) {
case any::Int : os << x.intVal; break;
case any::Dbl : os << x.dblVal; break;
}
return os;
}
int main()
{
std::vector<any> vect;
any k1, k2;

vect.emplace_back(3);
vect.emplace_back(4);
vect.emplace_back(9.5);
vect.emplace_back(10.5);

for (const auto& i: vect)
std::cout << i << " ";
}

关于c++ - 错误 : Variable Not declared in this scope,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42082111/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com