在下面类声明中,关于生成对象不正确的是( )。 class point { public: int x; int y; point(int a,int b) {x=a;y=b;} }; A. point p(10,2); B. point *p=new point(1,2); C. point *p=new point[2]; D. point *p[2]={new point(1,2), new point(3,4)};
时间: 2024-02-05 21:03:37 浏览: 326
关于生成对象不正确的是 C 选项,`point *p=new point[2];`。这是因为 `point` 类中没有默认的构造函数,所以不能使用数组的方式创建对象,否则会导致编译错误。正确的方式是使用 `new` 运算符逐个创建对象,或者添加默认构造函数。其他选项都是正确的方式创建对象:
- A 选项:通过有参构造函数直接创建对象。
- B 选项:通过 `new` 运算符创建单个对象,并返回指向该对象的指针。
- D 选项:通过 `new` 运算符创建两个对象,并分别将指针存储在数组中。
相关问题
Point_2D(int x,int y):Point(x),y(y){}
这是一个C++中的构造函数,用于创建一个二维点(Point_2D)对象,并且继承了Point类中的x属性,同时在Point类属性的基础上添加了y属性。其中,x和y都是整型(int)数据类型。
```cpp
class Point {
public:
int x;
Point(int x) : x(x) {} // 父类构造函数
};
class Point_2D : public Point {
public:
int y;
Point_2D(int x, int y) : Point(x), y(y) {} // 子类构造函数
};
```
在此代码中,Point类中只有一个参数为x的构造函数,而Point_2D类中的构造函数继承了父类Point中的x属性,同时在Point类属性的基础上添加了y属性。在构造函数中,使用冒号初始化语法调用父类构造函数,将x属性初始化为x,再将自身属性y初始化为y。
设计Point类的<<、>>运算符重载函数,并输入一个点再输出该点。 class Point { public: int x,y; Point(int i=0,int j=0) { x=i;y=j;} };
好的,以下是重载<<和>>运算符的代码实现:
```c++
#include <iostream>
using namespace std;
class Point {
public:
int x,y;
Point(int i=0, int j=0) { x=i; y=j; }
friend ostream& operator<<(ostream& out, const Point& p);
friend istream& operator>>(istream& in, Point& p);
};
ostream& operator<<(ostream& out, const Point& p) {
out << "(" << p.x << ", " << p.y << ")";
return out;
}
istream& operator>>(istream& in, Point& p) {
in >> p.x >> p.y;
return in;
}
int main() {
Point p;
cout << "请输入一个点:" << endl;
cin >> p;
cout << "你输入的点是:" << p << endl;
return 0;
}
```
这里我们使用了友元函数来重载运算符,重载函数中使用了输入输出流对象,让我们可以像使用cout和cin一样使用这些运算符来输入和输出Point类型的对象。在main函数中,我们创建了一个Point对象p,并通过cin输入一个点,然后通过cout输出该点。
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![](https://img-home.csdnimg.cn/images/20210720083646.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)