C ++中的类和变量范围 [英] Classes and variables scope in C++
问题描述
class car {
int speed;
double position;
public:
car(int v,double d);
int getspeed();
};
int car::getspeed() {
return speed;
}
car::car(int s, double x){
speed=s;
position=x;
}
即使我为car(int s,v)指定了不同的变量,为什么它有效吗?
i虽然应该给我一个编译时错误?
Even though i specified different variables for car(int s,v), why does it work? i though it should give me a compile time error?
此代码:它使用哪个变量?
this code:which var it uses?
class car {
int speed;
double position;
public:
car(int speed,double time);
int getspeed();
};
int car::getspeed() {
return speed;
}
car::car(int speed, double position){
speed=speed;
position=position;
}
我认为可以使用全局变量,或者可以使用它吗? t一定要说
I think the global variable might be used, or is it something you can't say certain about
推荐答案
car::car(int speed, double position){
speed=speed;
position=position;
}
在此函数定义中,它对类成员car :: speed不起作用和car :: position,因为您在函数参数列表中声明了本地int速度和double位置,因此它们隐藏了类成员变量。要正确执行此操作,您需要明确地这样说:
In this function definition, it does nothing with the class member car::speed, and car::position, because you declared the local int speed and double position in the function parameter list, they hide the class member variables. To do it properly, you need explicitly say so:
car::car(int speed, double position){
this->speed=speed;
this->position=position;
}
这篇关于C ++中的类和变量范围的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!