我有一个包含一些带有数组功能的类。其中一个称为pick,此函数没有数组,但是我想从其他函数中显示数组元素,一旦我编写了显示数组元素的代码,我就无法获取该元素,尽管代码可以正常工作,如果我添加普通文本也可以将显示但不能显示数组元素,我将附加以下代码:
#include <iostream>
#include<stdlib.h>
#include <string>
using namespace std;
// global variable
string plantType;
int temperatures ;
string water;
string sunExposure;
bool pet;
string plant1,plant2,plant3;
class inside{
public:
void low(){
string plant1 [3]={"Snake plant","Spider plant","Aloe Vera plant"};
for(int i =0; i<3; i++){
cout << "* "<< plant1[i]<<endl;
}
}
void medium(){
string plant2 [5]={"Pothos plant","Dracaena plant","ZZ plant","Rubber plant","Philodendron Green plant"};
for(int i =0; i<5; i++){
cout << "* "<< plant2[i]<<endl;
}
}
void high(){
string plant3 [2]={"Bird’s Nest Fern plant","Peace Lily plant"};
for(int i =0; i<2; i++){
cout << "* "<< plant3[i]<<endl;
}
}
void pick(){
cout <<"Best choice for you is: ";
if (temperatures >= 13 && temperatures <=29 ){
if(water=="low"){
if(sunExposure=="fully"){
cout<<"test"<<endl;
if(pet==true){
cout<<plant1[1]<<endl; //this line cannot be executed
}
}
}}}
int main(){
cout <<"Where do you want to grow the plant (inside), or (outside)"<<endl;
cin>>grow;
if (grow == "inside"){
//inside home
cout<<endl<<"inside"<<endl;
cout<<"Enter the Temperature in (Celsius scale 13-29)"<<endl;
cin>>temperatures;
cout<<"Enter water level (low - medium - high)"<<endl;
cin>>water;
cout<<"Enter Sun Exposure (fully - partly - shady)"<<endl;
cin>>sunExposure;
cout<<"Do you have pet (true or false)? "<<endl;
cin>>pet;
inside inside;
inside.pick();
}
}
字符串变量plant1[3]
,plant2[3]
和plant3[3]
仅对low()
,medium()
,high()
可见,但彼此不可见。例如,您正在尝试访问foo()
函数中bar()
函数的本地声明的变量,这是不可能的。
第二,您尝试访问plant1[3]
中的pick()
数据成员,但是编译器不知道在该函数之外您实际定义了这三个工厂的名称的地方,只是它知道plant1
变量而没有在类的私有部分中声明的数组。因此,您的代码很有可能会失败。
相反,您可以通过这种方式声明相同的内容:
class inside {
std::string plants1[3] = {"...", ...}; // these variables are
std::string plants2[3] = {"...", ...}; // only visible inside the
std::string plants3[3] = {"...", ...}; // class member functions
.
.
}
然后,您将成功执行该行。