gpt4 book ai didi

c++ - 点运算符和点运算符有什么意义?

转载 作者:太空狗 更新时间:2023-10-29 19:59:54 25 4
gpt4 key购买 nike

<分区>

我知道指向 (->) 和点 (.) 运算符之间的区别,但我不明白为什么需要这两个运算符?不使用指针而只使用点运算符不是总是那么容易吗?来自 http://www.programcreek.com/2011/01/an-example-of-c-dot-and-arrow-usage/

    #include <iostream>

using namespace std;

class Car
{
public:
int number;

void Create()
{
cout << "Car created, number is: " << number << "\n" ;
}
};

int main() {
Car x;
// declares x to be a Car object value,
// initialized using the default constructor
// this very different with Java syntax Car x = new Car();
x.number = 123;
x.Create();

Car *y; // declare y as a pointer which points to a Car object
y = &x; // assign x's address to the pointer y
(*y).Create(); // *y is object
y->Create();

y->number = 456; // this is equal to (*y).number = 456;
y->Create();
}

为什么要费心使用指针?只需像 X 一样创建 Y,它的工作原理是一样的。如果您说您需要动态分配内存的指针,那么为什么还要使用点运算符呢?

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com