设计一个类CPt,该类有两个数据成员x,y还有一个对象备份函数copy,copy功能如下:如果定义类A对象a1,a2,调用函数a1.copy(&a2)表示将对象a2的x,y赋值给对象a1的x,y(提示用this判断是否给自己赋值)
时间: 2023-04-02 09:04:43 浏览: 195
好的,这是一个关于设计类的问题。CPt类有两个数据成员x和y,还有一个备份函数copy。copy函数的功能是将对象a2的x,y赋值给对象a1的x,y。如果调用a1.copy(&a2),则需要判断是否给自己赋值,可以使用this指针来实现。具体实现如下:
```c++
class CPt {
public:
int x, y;
void copy(CPt* p) {
if (this != p) {
this->x = p->x;
this->y = p->y;
}
}
};
```
在copy函数中,首先判断this指针是否等于p指针,如果不等于,则将p指针所指对象的x,y值赋值给this指针所指对象的x,y值。这样就可以实现对象备份的功能了。
相关问题
设计一个三维流线类 CPline,定义点类 CPt3d ,有3个成员 x,y,z; 1、该类有属性:点坐标数组,点数; 2、该类有方法: a) 在线末尾添加一个点的函数 AppendPt b) 重载运算符 [] ,实现:设置和获取线上某点信息。 c) 重载运算符 = ,实现线的复制赋值; d) 将函数 AppendPt 重载为 + 运算。
下面是实现 CPt3d 类和 CPline 类的代码:
```cpp
#include <iostream>
#include <vector>
class CPt3d {
public:
CPt3d(double x = 0, double y = 0, double z = 0) : x_(x), y_(y), z_(z) {}
double x() const { return x_; }
double y() const { return y_; }
double z() const { return z_; }
private:
double x_, y_, z_;
};
class CPline {
public:
CPline() : pts_(), n_(0) {}
void AppendPt(const CPt3d& pt) {
pts_.push_back(pt);
++n_;
}
CPt3d& operator[](int i) { return pts_[i]; }
const CPt3d& operator[](int i) const { return pts_[i]; }
CPline& operator=(const CPline& other) {
pts_ = other.pts_;
n_ = other.n_;
return *this;
}
CPline operator+(const CPt3d& pt) const {
CPline new_line(*this);
new_line.AppendPt(pt);
return new_line;
}
int n() const { return n_; }
private:
std::vector<CPt3d> pts_;
int n_;
};
int main() {
CPline line;
line.AppendPt(CPt3d(0, 0, 0));
line.AppendPt(CPt3d(1, 0, 0));
line.AppendPt(CPt3d(1, 1, 0));
line.AppendPt(CPt3d(0, 1, 0));
line.AppendPt(CPt3d(0, 1, 1));
std::cout << "Line points:" << std::endl;
for (int i = 0; i < line.n(); ++i) {
std::cout << "(" << line[i].x() << "," << line[i].y() << "," << line[i].z() << ")" << std::endl;
}
CPline new_line = line + CPt3d(0, 0, 1);
std::cout << "New line points:" << std::endl;
for (int i = 0; i < new_line.n(); ++i) {
std::cout << "(" << new_line[i].x() << "," << new_line[i].y() << "," << new_line[i].z() << ")" << std::endl;
}
return 0;
}
```
运行结果如下:
```
Line points:
(0,0,0)
(1,0,0)
(1,1,0)
(0,1,0)
(0,1,1)
New line points:
(0,0,0)
(1,0,0)
(1,1,0)
(0,1,0)
(0,1,1)
(0,0,1)
```
已知一个模板类定义如下: temple <typename T1 > class CPt{ public: 共 7 页 第4页 T1 m_x,m_y; }; 则想用 float 进行实例化,定义一个类对象 a 的语句是
使用模板类实例化时,需要在类名后面加上尖括号,并在括号内指定模板参数的类型。因此,如果想使用 float 类型实例化 CPt 模板类,并定义一个类对象 a,可以这样写:
```
CPt<float> a;
```
这样就定义了一个 CPt 模板类的实例,其中的模板参数 T1 被指定为 float 类型,对象名为 a。
阅读全文
相关推荐
















