c++ - 在一个文件中定义多个类时,我发现低类中的函数无法访问我的主函数
问题描述
#include <iostream>
#include <string>
using namespace std;
/*----------------RECTANGLE CLASS----------------*/
class rectangle {
int w, h;
public:
void setVals(int, int);
int area();
int perimeter();
};
void rectangle::setVals( int x, int y) {
w = x;
h = y;
}
int rectangle::area() {
return w * h;
}
int rectangle::perimeter() {
return (2 * w) + (2 * h);
}
/*----------------CIRCLE CLASS----------------*/
class circle {
double pi = 3.14159265358979;
double r;
void setR(double);
double area();
double circumference();
};
void circle::setR(double radius) {
r = radius;
}
double circle::area() {
return pi * (r * r);
}
double circle::circumference() {
return 2 * pi * r;
}
/*----------------MAIN FUNCTION----------------*/
int main() {
int choice;
cout << "Enter 1 if you would like to calculate the area of a rectangle, Enter 2 if you would like calculate the area of a circle";
cin >> choice;
if (choice == 1) {
int width, height;
cout << "Enter the width of the rectangle ";
cin >> width;
cout << "Enter the height of the rectangle ";
cin >> height;
rectangle r;
r.setVals(width, height);
cout << "The area of the rectangle is " << r.area() << "\n";
cout << "The perimeter of the rectangle is " << r.perimeter() << "\n";
}
else if (choice == 2) {
double r;
cout << "Enter the radius of the circle ";
cin >> r;
circle c;
c.setR(r);
cout << "The area of the circle is " << c.area(); << "\n"l;
cout << "The circumference of the circle is " << c.circumference() << "\n";
}
return 0;
}
这只是一个在 C++ 中掌握 OOP 窍门的练习程序,我知道 C++ 是自上而下编译的(所以你的主函数必须低于它正在使用的任何变量和对象),但从我所拥有的看到了,在单个 .cpp 文件中创建两个类应该没有任何问题,但我遇到了这个问题。非常感谢任何帮助,谢谢。
解决方案
的成员函数circle
没有标记public
。
它与多个类无关;只是您的第二类定义不正确。
推荐阅读
- angular - 如何为 Angular 应用程序设置 Azure 管道
- jupyter-notebook - 为什么我会收到错误消息:TypeError:'str' 和 'int' 的实例之间不支持'<='?
- python - 有条件地将数据拆分为训练和测试(Pandas)
- python - 如何在 Keras 中裁剪一个张量,每个子张量都有不同的裁剪值?
- php - 如何排除输出错误日志中生成的服务器信息
- sql-server - MySQLServer:检查组中是否存在条件,然后标记整个组
- html - 单页应用程序中的图像问题
- java - 使用 GridBagLayout 时没有出现画布
- linux - 无法从 bash 脚本中保存历史记录
- json - 对于各种版本的 PostgreSQL,使用 JSON 进行奇怪的不同工作