作用域问题?
#include <iostream>#include <vector>
using namespace std;
class stack{
public:
stack();
stack(int);
void opp();
private:
int num;
};
stack::stack()
{
num = 120;
}
stack::stack(int new_num)
{
num = new_num;
}
void stack::opp()
{
vector<int> s;
int i = 2;
while (i != num)
{
bool on = true;//
for (int j = 2; j != i; ++j)
{
if (i % j == 0)
{
on = false;
break;
}
}
if (on)
{
s.push_back(i);
}
i++;
}
for (int k = s.size() - 1; k >= 0; --k)
cout << s[k] << " ";
}
int main()
{
stack f;
f.opp();
cout << "\n";
cout << "Please enter an integer:";
int a;
cin >> a;
stack k(a);
k.opp();
return 0;
}
与
#include <iostream>
#include <vector>
using namespace std;
class stack{
public:
stack();
stack(int);
void opp();
private:
int num;
};
stack::stack()
{
num = 120;
}
stack::stack(int new_num)
{
num = new_num;
}
void stack::opp()
{
vector<int> s;
int i = 2;
bool on = true;
while (i != num)
{
for (int j = 2; j != i; ++j)
{
if (i % j == 0)
{
on = false;
break;
}
}
if (on)
{
s.push_back(i);
}
i++;
}
for (int k = s.size() - 1; k >= 0; --k)
cout << s[k] << " ";
}
int main()
{
stack f;
f.opp();
cout << "\n";
cout << "Please enter an integer:";
int a;
cin >> a;
stack k(a);
k.opp();
return 0;
}所得的结果不同,这是为什么,放在while里面的变量跟放在外面的有什么区别?