结构定义的语法
结构类型是一种用户定义的复合类型。结构可由一些不同类型的成员组成。
struct structName { memberList };
实例:
struct Person
{
String name;
int age;
float weight;
};
每个结构成员的类型可以是基本类型、其它VSL结构或C/C++结构/类。这些类型的数组成员也被支持。
struct Car
{
Entity3D entity;
Person passengers[4];
float weight;
Vector velocity;
};
要访问结构的成员,你得使用 "." 运算符。
void SetPerson(Person p, String name, int age, float weight)
{
// Set name
if (name == "")
p.name = "Unknown";
else
p.name = name;
// Set age
if (age < 0)
age = 1;
p.age = age;
// Set weight
if (weight < 0)
weight = 40;
p.weight = weight;
}
void main()
{
Car car;
car.entity = null;
car.velocity.Set(0,0,0);
car.weight = 1500;
// Set persons
for (int i = 0; i < 4; ++i)
{
String name("Passengers");
name += i;
SetPerson(car.passengers[i], name, rand()*20+20, rand()*30+60);
// Add person weight to the car weight
car.weight += car.passengers[i].weight;
}
}
在结构上使用运算符 =, == 及 !=
当在结构上使用 =, == 及 != 运算符时,VSL编译器为每个具有这种被重载运算符的成员调用合适的运算符。
对于那些没有重载运算符的成员,这个代码会产生:
Operator =
Code is generated to copy memory.
Operator == and !=
Code is generated to compare memory.
实例:
Person p1;
Person p2;
String name("john");
SetPerson(p1, name, 30, 75);
p2 = p1;
等价于:
p2.name = p1.name; // call the String operator =
p2.age = p1.age;
p2.weight = p1.weight;
p2 == p1;
等价于:
p2.name == p1.name; // call the String operator ==
p2.age == p1.age;
p2.weight == p1.weight;
p2 != p1;
等价于:
p2.name != p1.name; // call the String operator !=
p2.age != p1.age;
p2.weight != p1.weight;