有两个点和点运算符有什么意义?

Cel*_*tas 3 c++ syntax pointers

我知道点到( - >)和点(.)运算符之间的区别,但我不明白为什么需要两个arrises?是不是总是那么容易不使用指针而只是使用点运算符?来自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();
    }
Run Code Online (Sandbox Code Playgroud)

为什么要打扰使用指针?只需创建Y作为X,它将工作相同.如果你说你需要动态分配内存的指针,那么为什么还要使用点运算符呢?

jal*_*alf 6

我认为你在混合两个不同的问题.

首先,->操作员是不必要的,是的.x->y相当于(*x).y,但->操作员更容易打字,所以它基本上只是一个方便.

第二部分是是否使用指针.而你是对的,通常你不应该.默认情况下,只需在那里创建对象,然后引用它们:

Foo bar;
bar.baz():
Run Code Online (Sandbox Code Playgroud)

但很多情况下指针仍然是必需的.对象需要能够引用其他对象.引用可以做到这一点,但不能重新安装.初始化后,它将始终指向同一个对象.

可以更新指针以指向不同的对象.

链接列表,树数据结构和无数其他东西依赖于能够指向其他对象的对象.

所以是的,我们需要指针.但是,我们并不需要的->操作.我们只是使用它,因为它很方便.