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

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

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-13 22:21
    关注

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

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
    计算机小混子 2022-04-14 06:18

    边敲边学啊

    回复
    金士顿 回复 计算机小混子 2022-04-14 06:26

    可以,思路是对的,我的建议还是先看一遍书,再第二遍看书的时候练习

    回复
    计算机小混子 回复 金士顿 2022-04-16 06:37

    光看经常看不懂

    回复
    展开全部4条评论
查看更多回答(1条)
编辑
预览

报告相同问题?

问题事件

  • 系统已结题 4月21日
  • 已采纳回答 4月14日
  • 创建了问题 4月13日
手机看
程序员都在用的中文IT技术交流社区

程序员都在用的中文IT技术交流社区

专业的中文 IT 技术社区,与千万技术人共成长

专业的中文 IT 技术社区,与千万技术人共成长

关注【CSDN】视频号,行业资讯、技术分享精彩不断,直播好礼送不停!

关注【CSDN】视频号,行业资讯、技术分享精彩不断,直播好礼送不停!

客服 返回
顶部