计算机小混子 2022-04-14 04:08 采纳率: 100%
浏览 23
已结题

关于动态数组类求解释下面几个问题

Point& element(int index)这是什么函数为什么还有&?
points.element(0).move(5, 0);这是啥为什么points还能调用element?


// 6-18动态数组类.cpp : 此文件包含 "main" 函数。程序执行将在此处开始并结束。
//

#include <iostream>
#include <cassert>
using namespace std;
class Point {
public:
    Point() : x(0), y(0) {
        cout << "Default Constructor called." << endl;
    }
    Point(int x, int y) : x(x), y(y) {
        cout << "Constructor called." << endl;
    }
    ~Point() { cout << "Destructor called." << endl; }
    int getX() const { return x; }
    int getY() const { return y; }
    void move(int newX, int newY) {
        x = newX;
        y = newY;
    }
private:
    int x, y;

};
//动态数组类
class ArrayofPoints {
public:
    ArrayofPoints(int size) :size(size) {
        points = new Point[size];
    }
    ~ArrayofPoints() {
        cout << "Deleting..." << endl;
        delete[]points;
    }
    //获得下标为index的的元素
    Point& element(int index) {
        assert(index >= 0 && index < size);//如果下标越界,程序终止
        return points[index];
    }
private:
    Point* points;//指向动态数组首地址
    int size;//数组大小
};
int main()
{
    int count;
    cout << "Please enter the count of points:";
    cin >> count;
    ArrayofPoints points(count);//创建对象数组
    points.element(0).move(5, 0);
    points.element(1).move(15, 20);
    return 0;
}



  • 写回答

2条回答 默认 最新

  • 金士顿 2022-04-14 06:21
    关注

    Point& element(int index) 返回值是引用啊,多看看c++的基础是我,不要着急写代码

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

问题事件

  • 系统已结题 4月22日
  • 已采纳回答 4月14日
  • 创建了问题 4月14日

悬赏问题

  • ¥15 smptlib使用465端口发送邮件失败
  • ¥200 总是报错,能帮助用python实现程序实现高斯正反算吗?有偿
  • ¥15 对于squad数据集的基于bert模型的微调
  • ¥15 为什么我运行这个网络会出现以下报错?CRNN神经网络
  • ¥20 steam下载游戏占用内存
  • ¥15 CST保存项目时失败
  • ¥15 树莓派5怎么用camera module 3啊
  • ¥20 java在应用程序里获取不到扬声器设备
  • ¥15 echarts动画效果的问题,请帮我添加一个动画。不要机器人回答。
  • ¥15 Attention is all you need 的代码运行