【发布时间】:2020-05-17 10:03:16
【问题描述】:
我的课-:用于创建、显示对角矩阵
class Diagonal {
private:
int *A;
int n;
public:
Diagonal(){
n=2;
A = new int[n];
}
Diagonal(int n){
this->n = n;
A = new int[n];
}
void Create(){
cout<<"Enter the Elements : "
for(int i =0; i<=n; i++){
cin>>A[i-1];
}
}
void Set(int i, int j, int x){
if(i==j){
A[i-1] = x;
}
}
int Get(int i, int j){
if(i == j){
return A[i-1];
}
else{
return 0;
}
}
void display(){
for(int i=1; i<n; i++){
for(int j=1; j<n; j++){
if(i==j){
cout<<A[i-1]<<" ";
}
else{
cout<<"0 ";
}
}
cout<<endl;
}
}
~Diagonal(){
delete []A;
}
};
void functionName(){
cout<<"----- Functions ------"<<endl;
cout<<"1. Create "<<endl;
cout<<"2. Get "<<endl;
cout<<"3. Set "<<endl;
cout<<"4. Display "<<endl;
cout<<"5. Exit "<<endl;}
带有嵌套do-while循环和switch case的主函数:
int main(){
int ch,fun;
do{
cout<<"------ Menu --------"<<endl;
cout<<"1. Diagonal "<<endl;
cout<<"2. Lower Tri-angular "<<endl;
cout<<"3. Upper Tri-angular "<<endl;
cout<<"4. Tri-diagonal"<<endl;
cout<<"5. Toplitz"<<endl;
cout<<"6. Exit"<<endl;
cout<<endl;
cin>>ch;
do{
int n;
switch(ch)
{
case 1: functionName();
cin>>fun;
switch(fun){
case 1:
{
cout<<"Enter the size of matrix : " ;
cin>>n;
Diagonal d(n);
d.Create();
}
break;
case 2:
//how to call d.get();
break;
case 3:
//how to call d.set();
break;
case 4:
//how to call d.display();
break;
case 5:
break;
}
break;
case 2: functionName();
break;
case 3: functionName();
break;
case 4: functionName();
break;
case 5: functionName();
break;
}
}while(fun<4);
}while(ch<=5);
return 0;
}
我的问题是如何在不同的 switch case 中为 case 1 创建的同一个 obj 调用类成员函数?
- 如何调用 d.get();情况2
- 如何调用 d.set();情况 3
当我调用这些成员函数时发生错误,“d is not declared in this scope” 有没有办法在switch语句中调用这些成员函数?
【问题讨论】:
标签: c++ class switch-statement member-functions