[英]How to access the data member of one function into another function inside same class in c++
我想將字符串數組聲明為用戶提供的限制。 所以我在 getData() 中取了限制,並在 getData 函數中聲明了字符串。 總的來說,我想取學生的名字並將其顯示在同一個班級中。 對不起,基本問題,提前謝謝你。
class student
{
int limit;
public:
void getData()
{
cout<<"Enter the number of students: ";
cin>>limit;
string name[limit];
cout<<"Enter the names of students: \n";
for(int i=0; i<limit; i++)
cin>>name[i];
}
void showData()
{
cout<<"The list of students: \n";
for(int i=0; i<limit; i++)
cout<<name[i]<<endl;
}
};
int main()
{
student s1;
s1.getData();
s1.showData();
return 0;
}
在此函數中,錯誤來自“名稱未在此范圍內聲明”。 如果是廢話,請提前道歉。
void showData()
{
cout<<"The list of students: \n";
for(int i=0; i<limit; i++)
cout<<name[i]<<endl;
}
您的代碼的一個問題是string name
是在getData()
中定義的,而不是在showData()
中定義的。 我要做的是聲明一個成員變量vector<string> name
,就像你對int limit
所做的那樣。 我會使用向量而不是數組,因為它更容易為我編寫代碼。
#include <iostream>
#include <vector>
using namespace std;
class student
{
int limit;
vector<string> name;
public:
void getData()
{
cout<<"Enter the number of students: ";
cin>>limit;
cout<<"Enter the names of students: \n";
for(int i=0; i<limit; i++)
{
string temp;
cin>>temp;
name.push_back(temp);
}
}
void showData()
{
cout<<"The list of students: \n";
for(int i=0; i<limit; i++)
cout<<name[i]<<endl;
}
};
int main()
{
student s1;
s1.getData();
s1.showData();
return 0;
}
輸出:
Enter the number of students: 3
Enter the names of students:
andy
max
rose
The list of students:
andy
max
rose
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.