首页 > 解决方案 > 在一个文件中定义多个类时,我发现低类中的函数无法访问我的主函数

问题描述

#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 文件中创建两个类应该没有任何问题,但我遇到了这个问题。非常感谢任何帮助,谢谢。

标签: c++

解决方案


的成员函数circle没有标记public

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


推荐阅读