参考《C++语言程序设计(第4版)第6章 数组、指针与字符串 例6-18 动态数组类》
在学习过程中记录几类容易混淆的概念
- 指针的运算(前置++、后置++)
y=*px++ 和 y=*(px++)区别 - 常量指针和指针常量
const int *p1=&a;//指向常量的指针
int * const p2=&a;//指针类型的常量(指针本身的值不能改变) - 二维数组指针访问方式
((a+i)+j)
*(a[i]+j)
*(a+i)[j]
(a+ni+j) - 指针数组和数组指针
int (*p)[5] 数组指针
int *p[5] 指针数组 - 函数指针
数据类型 (* 函数指针名[常量表达式])(参数表) - 对象指针
①一般概念
②this指针
③指向类的非静态成员的指针
④指向类的静态成员的指针
实例代码
创建Point类的数组ArrayOfPoints
Point.h
#pragma once
class Point {
public:
Point();
Point(int x, int y);
~Point();
void move(int newX, int newY);
int getX() const { return x; }
int getY() const { return y; }
private:
int x, y;
};
Point.cpp
#include <iostream>
#include "Point.h"
using namespace std;
Point::Point() :x(0), y(0) {
cout << "Default Constructor called." << endl;
}
Point::Point(int x, int y) : x(x), y(y) {
cout << "Constructor called." << endl;
}
Point::~Point() {
cout << "Destructor called." << endl;
}
void Point::move(int newX, int newY) {
cout << "Moving the point to (" << newX << "," << newY << ")" << endl;
x = newX;
y = newY;
}
ArrayOfPoints.h
#pragma once
#include "Point.h"
class ArrayOfPoints {
public:
ArrayOfPoints(int size);
~ArrayOfPoints();
Point& element(int index);
private:
Point* points;
int size;
};
void CreateArrayOfPoints();
ArrayOfPoints.cpp
#include <iostream>
#include <cassert>
#include "Point.h"
#include "ArryayOfPoints.h"
using namespace std;
ArrayOfPoints::ArrayOfPoints(int size): size(size) {
points = new Point[size];
}
ArrayOfPoints::~ArrayOfPoints() {
cout << "Deleting..." << endl;
delete[] points;
}
Point& ArrayOfPoints::element(int index) {
assert(index >= 0 && index < size);
return points[index];
}
void CreateArrayOfPoints() {
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);
}
1890


&spm=1001.2101.3001.11974&articleId=107312030&d=1&t=3&u=e1a16a2e6f4d4cc9b8f19850f97e236d)

被折叠的 条评论
为什么被折叠?



