为什么主函数中"cout<<"处会报错?
时间: 2023-07-19 08:41:04 浏览: 115
在主函数中 `cout << tri.area() << endl` 和 `cout << rect.area() << endl` 处会报错,是因为 `area()` 函数的返回值是 `double` 类型,而 `cout` 输出流只能输出字符串和字符类型、整型、浮点型等基本数据类型。因此需要将 `area()` 函数的返回值转换为字符串类型后再进行输出,可以使用 `to_string()` 函数将 `double` 类型转换为字符串类型,具体代码如下:
```
cout << ". The area is " << to_string(tri.area()) << endl;
// 或者使用 printf 函数输出,如下:
// printf(". The area is %f\n", tri.area());
```
同样的修改也需要在 `rect.area()` 输出处进行。
相关问题
改正以下程序中的错误,并分析错误原因,不得更改主函数。 #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]; }
程序中有两个错误:
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 Base { protected: void fun()const{cout<<"fun";} void fun2()const{cout<<"fun2";} void fun3()const{cout<<"fun3";} }; class Der:public Base { public: void fun4()const{cout<<"fun4";} }; int main() { Der obj; obj.fun(); obj.fun2(); obj.fun3(); obj.fun4(); }为什么有错
在上面的代码中,在派生类Der中,将Base类的继承方式设置为public,表示派生类Der可以访问Base类的公有成员和保护成员。因此,在主函数中,通过Der类的对象obj来访问Base类的成员函数是可以实现的。
但是在这段代码中,fun2()函数和fun3()函数被设置成了protected,在派生类Der中无法直接访问。因此,在主函数中通过对象obj来调用fun2()函数和fun3()函数时,程序会报错。
如果将fun2()函数和fun3()函数的访问权限改为public,程序就可以正常运行了。因此,将Base类中fun2()函数和fun3()函数的访问权限改为public即可解决这个问题。