改正以下程序中的错误,并分析错误原因,不得更改主函数。 #include<iostream> using namespace std; class Point { private: int x1,x2; public: Point(int x,int y) {x1=x;x2=y;} int x_cord(){return x1;} int y_cord(){return x2;} } main() { Point data(5,6); cout<<data.x_cord()<<endl; cout<<data.y_cord()<<endl; Point more_data[20]; }
时间: 2024-03-24 11:37:08 浏览: 16
程序中有两个错误:
1. 类 Point 的定义缺少分号;
2. main 函数的返回类型应该是 int。
以下是修改后的程序:
```c++
#include<iostream>
using namespace std;
class Point {
private:
int x, y;
public:
Point(int x, int y) {
this->x = x;
this->y = y;
}
int x_cord() { return x; }
int y_cord() { return y; }
};
int main() {
Point data(5, 6);
cout << data.x_cord() << endl;
cout << data.y_cord() << endl;
Point more_data[20];
return 0;
}
```
错误原因分析:
1. 类的定义缺少分号,导致编译器无法正确解析该类的定义,从而报错。
2. main 函数的返回类型应该是 int,因为 main 函数是程序的入口函数,程序在执行完 main 函数后会返回一个整数值给操作系统,用于表示程序的运行状态。如果没有返回值或返回值类型不为 int,编译器会报错。
相关问题
#include<iostream> using namespace std; class point { private; float x,y; public: void init(float,float); void show(); } void init(float a,float b) { x=a; y=b; } void show() { cout<<x<<"--"<<y<<endl; } void main() { point p; init(10.5,50.5); show(); }找出其中错误并改正
有几个错误需要修正:
1. 在类定义中,`private`和`public`应该以冒号结尾。
2. 在类定义中,成员变量x和y应该在`private`关键字下声明。
3. 在类定义中,成员函数init和show应该在`public`关键字下声明。
4. 在成员函数定义中,应该在函数名前加上类名point。
5. 在成员函数定义中,应该使用作用域解析运算符`::`来访问类的成员变量和成员函数。
6. 在主函数中,应该使用对象p来调用成员函数init和show。
下面是修改后的代码:
```c++
#include<iostream>
using namespace std;
class point {
private:
float x,y;
public:
void init(float,float);
void show();
};
void point::init(float a,float b) {
x=a;
y=b;
}
void point::show() {
cout<<x<<"--"<<y<<endl;
}
int main() {
point p;
p.init(10.5,50.5);
p.show();
return 0;
}
```
修改后的代码中,类的成员变量和成员函数已经被正确访问,代码可以正确运行。
判断两条直线是否垂直 ,部分代码提供,“***” 部分请补充完整。 #include <iostream> using namespace std ; class point //定义 点 类 { public: point() ; int get_x() ; int get_y() ; private: int x, y ; } ; point::point() { int r,c; cin >>r; cin >>c; x = r; y
好的,这是一个关于C++类和对象的问题。下面是代码示例:
```cpp
#include <iostream>
using namespace std;
class point { // 定义点类
public:
point();
int get_x();
int get_y();
private:
int x, y;
};
point::point() {
int r, c;
cin >> r;
cin >> c;
x = r;
y = c;
}
int point::get_x() {
return x;
}
int point::get_y() {
return y;
}
int main() {
point p1, p2; // 定义两个点对象
int x1 = p1.get_x();
int y1 = p1.get_y();
int x2 = p2.get_x();
int y2 = p2.get_y();
if ((x2 - x1) * (y2 - y1) == -1) { // 判断两条直线是否垂直
cout << "两条直线垂直" << endl;
} else {
cout << "两条直线不垂直" << endl;
}
return 0;
}
```
在这个程序中,首先定义了一个点类 `point`,它有两个私有成员 `x` 和 `y`,以及一个公有构造函数和两个公有成员函数 `get_x` 和 `get_y`,用于获取点的坐标。在构造函数中,通过 `cin` 输入点的坐标。
在主函数中,先定义了两个点对象 `p1` 和 `p2`,分别输入它们的坐标。然后判断两条直线是否垂直,这可以通过判断两条直线的斜率是否互为相反数来实现。如果两条直线的斜率乘积为 -1,则它们垂直;否则,它们不垂直。最后输出判断结果。
注意:这个程序只是判断两条直线是否垂直,并不是计算两条直线的斜率。如果想计算两条直线的斜率,需要在 `point` 类中增加一个成员函数,用于计算两个点之间的斜率。