技术干货十四:WSL Ubuntu Linux C++类与对象
WSL Ubuntu Linux C++类与对象
1 C++类与对象
This article explains how to read/write to structs and classes. The following code shows lines of code that do the job.
本篇讲解如何读/写结构体和类。下面的代码显展示了读/写结构体和类的方法
Robot_Struct robot_1;
Robot_Class robot_2;
robot_1.id = 2;
robot_1.robot_name = "Mobile robot";
robot_2.id = 3;
robot_3.robot_name = "Humanoid robot";
Similar to the struct instance, we can create an instance of a class and that is called an object.
与结构体实例类似,我们可以创建一个类的实例,称为对象。
Let’s look at Robot_Class robot_2
; here, robot_2
is an object and robot_1
is an instance of the structure. Using this instance or object, we can access each variable and function. We can use the .
operator to access each variable. The struct and class variables are accessed by using the .
operator. If you use struct or class pointers, you have to use the -> operator to access each variable. The following code is an example.
让我们来看看Robot_Class robot_2
;在这里,robot_2
是一个对象,而robot_1
是结构体的一个实例。使用这个实例或对象,我们可以访问每个变量和函数。我们可以使用.
运算符访问每个变量。使用.
运算符可以访问结构和类变量。如果使用结构或类指针,则必须使用->
运算符来访问每个变量。例如下面这串代码。
Creating a C++ Object and Accessing Object by Reference
创建C++对象并通过引用访问对象
Robot_Class *robot_2;
robot_2 = new Robot_Class;
robot_2->id - 2;
robot_2->name = "Humanoid Robot";
The new operator allocates memory for the C++ object. We can access the functions inside the class and print all values by using the .
operator. The following code shows how to do that.
新操作符为C++对象分配内存。我们可以访问类中的函数,并使用.
运算符打印所有值。下面的代码显示了如何执行此操作。
cout<<"ID="<<robot_1.id<<"\t"<<"Robot Name"<<robot_1.
robot_name<<endl;
cout<<"ID="<<robot_2.id<<"\t"<<"Robot Name"<<robot_2.
robot_name<<endl;
robot_2.move_robot();
robot_2.stop_robot();
We can save the code as class_struct.cpp, and compile it by using the following command.
我们可以将代码另存为class_struct.cpp,并使用以下命令编译它。
另存为class_struct.cpp 参考文章WSL Ubuntu Linux OOP基本概念中的代码,将其另存为class_struct.cpp 而后编译即可。
g++ class_struct.cpp -o class_struct
./class_struct