0
Pointers in class
How to use the pointer to get the value of a variable in class? Is it possible? class myclass{ int a = 1; int* p = &a; }; int main(){ myclass a; cout << a.*p; // - error }
3 Respuestas
+ 11
Your class variables are private and hence cannot be called directly by main function. Make them public by using the public access specifier.
It is also generally not encouraged to initialise class variables during declaration.
+ 11
// Well, this works.
#include <iostream>
using namespace std;
class myclass{
public: myclass()
{
a = 1;
p = &a;
}
int a;
int *p;
};
int main()
{
myclass a;
cout << *(a.p);
}
0
I found something... but how it works?
class myclass{
int speed = 1;
};
int main(){
int Car::*pSpeed = &Car::speed;
Car c1;
c1.speed = 1; // direct access
cout << "speed is " << c1.speed << endl;
c1.*pSpeed = 2; // access via pointer to member
cout << "speed is " << c1.speed << endl;
}