Problem about usage of "this" keyword in C++
class Monitor
{
private:
int 开发者_如何学编程rate;
Monitor(int rate)
{
this.rate = rate;
}
}
This is my code. I try to set the private member "rate" with local member that passes through constructor "rate". But I could use it like that In C#.
The error is:
expression must have class type
this
is a pointer, as others have said, but it's much better and more correct to use the base initializer list:
class Monitor
{
int rate;
public:
Monitor(int rate) : rate(rate) { }
};
That way, Monitor::rate
gets initialized to the right value, rather than first default-initalized and then assigned. For more general member objects this may in fact be the only legitimate way to initialize them.
class Monitor
{
private:
int rate;
Monitor(int rate)
{
this->rate = rate;
}
}
this needs to be treated like a pointer. Hence the ->
When you refer to this
, you're accessing a pointer to the object. What you want to do is:
Monitor(int rate)
{
this->rate = rate;
}
this
keyword represent a pointer to the current object.
You have to write:
this->rate = rate;
Dot notation is used if you have a instance of the class.
Monitor(int r)
{
rate = r;
}
Or better still:
Monitor(int r): rate(r)
{}
this->rate = rate. Pointers use the -> operator in C++.
Since this is a pointer to self, then you must use it as such. This fixes your problem :
class Monitor
{
private:
int rate;
Monitor(int rate)
{
this->rate = rate; // this is a pointer
}
};
Though it is perfectly legal C++ code, one should not use same names for argument(s) and member(s) of a class. Better implementation would be:
class Monitor
{
private:
int Rate; // Or m_nRate
public:
Monitor(int rate /* OR nRate */) : Rate(rate) /* m_nRate(nRate);*/
// OR
Monitor(int rate /* OR nRate */)
{
Rate = rate; // this->Rate = rate; // this->m_nRate = nRate;
}
};
精彩评论