0
we cannot create object of any class in switch case directly. Why?
#include <iostream> using namespace std; class Student{ string name; }; int main() { int n=1; switch(n){ case 1: Student s1; break; default: break; } return 0; }
7 Respuestas
+ 7
Notice that the switch statement body is enclosed in braces { }. These define the beginning and end of a basic block of code. Any variables (or objects) defined with a basic block exist only within that block. It is a principle known as scope. When execution goes outside the block, the variables defined within the block go out of scope and are discarded. They become inaccessible.
+ 3
you can use pointers
#include <iostream>
using namespace std;
class Student{
string name{"John"};
public:
Student()=default;
Student(const string& n):name(n){
cout<<name<<endl;
}
void sayname(){
cout<<"I am "<<name<<endl;
}
};
int main() {
int n=1;
Student* s1;
switch(n){
case 1:
s1 = new Student();
break;
case 2:
s1 = new Student("Jane");
break;
default:
break;
}
s1-> sayname();
}
+ 1
add braces:
switch(n) {
case 1:
{
Student s1;
break;
}
default:
break;
}
+ 1
john ds
s1 still only exists within the block scope of the braces.
+ 1
Bob_Li my bad, i thought he had a compiler error and as long he not use it anywhere else outside the block i assumed he asking why cannot compile it
0
Please show your code.
0
using unique_ptr
https://sololearn.com/compiler-playground/c3YvXqrdi4WS/?ref=app