我的课程-:用于创建,显示对角矩阵
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循环和切换大小写的主要功能:
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;
}
我的问题是如何在案例1中创建的相同obj的不同切换案例中调用类成员函数?
- 如何调用d.get();如果是2
- 如何调用d.set();如果是3
当我调用这些成员函数时发生错误,“在此范围内未声明d”有什么方法可以在switch语句中调用这些成员函数?
您可以使用唯一的指针:
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;
auto d = std::make_unique<Diagonal>();
switch(ch)
{
case 1: functionName();
cin>>fun;
switch(fun){
case 1:
{
cout<<"Enter the size of matrix : " ;
cin>>n;
d = std::make_unique<Diagonal>(n);
d->Create();
}
break;
case 2:
//how to call d.get();
d->get();
break;
case 3:
//how to call d.set();
d->set();
break;
case 4:
//how to call d.display();
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;
}