0
How Do I assign a variable in a class by using = operator (like we do with int, string and the other data types) ?
As I said in the title above, how can I do it ?
3 odpowiedzi
+ 1
I just want to initialize a variable which is inside the class.
f.e
class Klass{
int x;
}
main(){
Klass ks = 5;
}
and this is gonna set the x variable to 5.
I want something like that
+ 1
So, you want something like this:
#include <iostream>
using namespace std;
class Klass{
public:
int value;
};
int main() {
Klass k;
k.value = 5;
cout << "Value: " << k.value << endl;
return 0;
}
Observe that your class do not have any constructor, but the default one is still there. In addition, to dirctly access a variable inside an object you need such variable to be public. Last, in main() you need to first instantiate your object and after that you can access its members.
That is it.
0
Hi Mustafa,
I did not understood your question very well.
Do you want to initialize a variable that you declared inside a class using operator =?
Or do you want to initialize the entire class object with operator =?
Could you explain better what you want?