例如,即使您甚至可以修改对象外部的数据(我在此示例中使用的是struct),我也不明白在对象内部具有函数的意义是什么
int lamborghini_horsepower1 = 350;
struct car {
string model;
string color;
int horsepower;
void check(int horsepower) {
if (horsepower > 349) {
cout << "this car has many horsepowers";
}
}
};
car ford;
ford.check(lamborghini_horsepower1);
在这种情况下,它将始终运行。 如果该函数只能在对象的数据内部进行操作,那将是有意义的,因为正如它们所说的那样,它们是对象的数据,为什么函数可以访问其他变量?例如,如果在这种情况下传递另一个变量lamborghini_horsepower不属于福特对象,该怎么办?并且即使它们是不同的,仍然可以被福特的功能所困扰。
班级不同吗?
答案 0 :(得分:0)
在结构中,函数不会产生太大影响,因为可以从外部修改数据。但是,它们仍然可以充当便利功能,尤其是在正确编写时。您的函数将horsepower
作为参数,这是不必要的,因为horsepower
已经是结构中的一个字段。如果您将功能更改为:
void check() {
if (horsepower > 349) {
cout << "this car has many horsepowers" << endl;
}
}
您可以使用ford.check()
进行调用,它将自动从horsepower
变量中检索ford
。在类中,可以将字段声明为私有字段,这意味着不能从外部访问它们,并且必须仅使用类内部定义的函数进行修改。>
答案 1 :(得分:-1)
班级不同吗?
默认情况下,无法从外部访问类,如果可以,则
class car{
string model;
string color;
int horsepower;
void check(int horsepower) {
if(horsepower>349)
{
cout << "this car has many horsepowers";
}
}
};
然后该类中的任何内容都无法从类外部访问。但是,有一种方法可以修改可以使用access modifiers从外部访问哪些变量和函数。
使函数和变量在对象外部不可访问的目的是防止它们被意外调用或更改
简短的答案是您的示例对对象的效率不是很高。在该示例中,我只是将函数保留在struct之外。
类和结构的目的是将变量和函数放入一个包中。您拥有的示例不需要对象。对象设计的基础是通过赋予现实世界的对象功能(函数)和属性(变量)来模仿它们。
此处的check()
功能不是我们通常在汽车中发现的功能。相反,汽车具有某些属性,如颜色,速度和方向。汽车还具有加速,倒车,左转和右转的能力。这样我们就可以创建具有这些属性(变量)和能力(功能)的汽车对象
struct Car
{
int speed;
std::string color;
std::string direction;
Car() // As soon as the object is created, this function will be called and set speed to 0.
{
speed = 0;
}
void speedUp()
{
speed += 5;
}
void slowDown()
{
speed -= 5;
}
void stop()
{
speed = 0;
}
void reverse()
{
stop() // This will stop the car first
speed -= 2; // Move the car backwords
}
void turnLeft()
{
direction = "left";
}
void turnRight()
{
direction = "right";
}
};
因此,现在您可以创建具有不同速度,方向和颜色的相同类\结构的不同对象。