在一个文件中定义多个类时,我发现我的主函数无法访问较低类中的函数

When defining multiple classes in one file, I am getting that functions in the lower class are inaccessible to my main function

本文关键字:函数 我的 访问 发现 一个 文件 定义      更新时间:2023-10-16
#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++自上而下编译(因此您的 main 函数必须位于它正在使用的任何变量和对象下方(,但从我所看到的,在单个.cpp文件中创建两个类应该没有任何问题, 然而我遇到了这个问题。非常感谢任何帮助,谢谢。

circle 的成员函数未标记为public

它与多个类无关;只是你的第二个类定义不正确。