Указатель на объект - PullRequest
0 голосов
/ 23 октября 2018

код работает правильно, но мне просто интересно, почему вызов функции Show () с помощью указателя может вернуть значение x, y, z объекту A, почему не адрес?Потому что указатель хранит адрес.Но как это может дать значение функции Show ()?

#include <iostream>
using namespace std;

class _3D {
    double x, y, z;
public:
    _3D(); 
    _3D(double initX, double initY, double initZ);

void Show() {
        cout << x << " " << y << " " << z << "\n";
    }
};

// Overloaded constructor
_3D::_3D(double initX, double initY, double initZ) {
    x = initX;
    y = initY;
    z = initZ;
    cout << "With arguments!!!\n";
}

// Class _3D constructor without arguments
_3D::_3D() {
    x = y = z = 0;
    cout << "No arguments!!!\n";
}

void main() {
    _3D A(3, 4, 0);
    _3D B;

// Creating a pointer and adding with the A object's address to the object of _3D type
    _3D*PA = &A;

    // Calling the function Show()
    PA->Show();


    system("pause");
}

1 Ответ

0 голосов
/ 23 октября 2018

PA является переменной указателя , которая указывает на адрес памяти .В вашем случае вы сделали так, чтобы PA указывал на область памяти A, используя: PA = & A.Когда вы используете оператор -> на PA, он перейдет в ячейку памяти, которую вы указали ранее (& A) , и СЧИТАЕТ данные с этого адреса .Вот и все.

Пример: 3D-класс с именем A по адресу 0x1000.(например: случайная ячейка памяти)

3D A; // Creating a 3D structure variable

// This is your 3D structure in memory now.
A: 0x1000: x    (x = offset 0)
   0x1004: y    (y = offset 4)
   0x1008: z    (z = offset 8)

// Create pointer to A variable
3D* PA = &A; // PA == 0x1000

// Shows the pointers are the same
std::cout << &A    << std::endl; // Prints 0x1000 (THE ADDRESS of A!!)
std::cout << PA    << std::endl; // Prints 0x1000 (THE ADDRESS of A!!)

// Remember, when using just PA->foo ... will READ the value by default
std::cout << PA->x << std::endl; // goto Address 0x1000, offset 0 (read x)
std::cout << PA->y << std::endl; // goto Address 0x1000, offset 4 (read y)
std::cout << PA->z << std::endl; // goto Address 0x1000, offset 8 (read z)

// If you want the get GET the address of x, y or z, do use & as normal.
// &PA->x  mean goto address PA, offset x, y or z, and then get the address
std::cout << &PA->x << std::endl; // Prints 0x1000
std::cout << &PA->y << std::endl; // Prints 0x1004
std::cout << &PA->z << std::endl; // Prints 0x1008

Просто попробуйте поэкспериментировать с указателями и памятью, и вы должны прийти к тем же выводам.

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...