网站建设销售经理职责,做网站一般多钱,速度超快的wordpress模板,做教案找资料有哪些网站在C中#xff0c;符号“-”用于访问指向对象的指针的成员。它也被称为箭头运算符或取消引用运算符。
使用“-”符号的基本语法是#xff1a;
对象指针-成员名称
这里#xff0c;object_pointer是指向对象的指针#xff0c;member_name是属于该对象的成员变量…在C中符号“-”用于访问指向对象的指针的成员。它也被称为箭头运算符或取消引用运算符。
使用“-”符号的基本语法是
对象指针-成员名称
这里object_pointer是指向对象的指针member_name是属于该对象的成员变量或函数。
示例
通过指针访问成员变量
#include iostream
using namespace std;class MyClass {
public:int myVar;
};int main() {MyClass* objPtr new MyClass(); // Creates an object of MyClass and assigns it to objPtrobjPtr-myVar 42; // Sets the value of myVar in the object pointed by objPtr to 42cout objPtr-myVar endl; // Outputs: 42delete objPtr; // Frees the memory allocated for the object pointed by objPtr
}注意“MyClass*objPtrnew MyClass”和“MyClass*objPtrnew MyClass[]”之间没有区别。这两个语句都是等效的并使用“new”关键字创建指向类MyClass实例的指针。唯一的区别是类型名和变量名之间的间距这会影响代码的可读性。有些程序员更喜欢在类型名称后面有一个空格而另一些则不喜欢。然而这纯粹是个人偏好的问题不会影响代码的功能或正确性。
通过指针调用成员函数
#include iostream
using namespace std;class MyClass {
public:void printHello() {cout Hello! endl;}
};int main() {MyClass* objPtr new MyClass(); // Creates an object of MyClass and assigns it to objPtrobjPtr-printHello(); // Calls the printHello() member function of the object pointed by objPtr and prints Hello! to the consoledelete objPtr; // Frees the memory allocated for the object pointed by objPtr
}