在一个文件中定义多个类时,我发现我的主函数无法访问较低类中的函数
When defining multiple classes in one file, I am getting that functions in the lower class are inaccessible to my main function
#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
。
它与多个类无关;只是你的第二个类定义不正确。
相关文章:
- 为什么我的删除节点函数实际上没有删除节点?
- 为什么在我的函数类型后使用引用运算符 (&) 允许我修改它返回的值?
- 模板,函数使用错误的构造函数来复制我的对象
- 为什么我的递归函数按降序打印,然后按升序打印?
- 为什么我的模板化函数需要从一个迭代器转换到另一个迭代器?
- 在哪里放置我的函数?进入我的母语 Gui 还是进入我的演示者?
- 为什么我的数组双精度函数不起作用?
- 移动赋值运算符;尝试引用已删除的函数.我该如何解决这个问题?
- 为什么我的双向链表删除函数会删除多个节点?
- 为什么在我的 main 函数中声明整数后我的整数数组中会出现错误?
- 如何返回实际值(在我的例子中是无符号字符数组)而不是来自 C++ 函数的指针?
- 为什么我的运算符 + 重载尽管是通过引用传递的,但仍调用我的复制构造函数?
- 为什么在尝试测量函数返回所需的时间时,我的运行时编号是错误的?
- 查找定义我的 C/C++ 函数/宏的文件比'grep'更简单的方法
- 为什么我的 while 函数没有终止?
- 为什么我的 constexpr 对象在我的函数中不是 constexpr?
- 我关于函数"Assert"的C++代码有问题
- 如何检测除整数以外的任何内容是否传递给我的类构造函数?
- 链表堆栈类的复制构造函数:我的正在向后复制
- 为什么在这种情况下没有调用复制构造函数-我的推理正确吗?