嗨我收到了我尝试过的“函数未在此范围内声明”的每个函数的错误。我是C ++的新手,并试图让我的TA解决这个问题,但仍然没有想到它。谢谢你的帮助!
这是我的头文件(circle.h):
#ifndef _CIRCLE_H_
#define _CIRCLE_H_
class circle
{
private:
double x1;
double x2;
double y1;
double y2;
protected:
double distance(double x1, double y1, double x2, double y2);
public:
double radius(double x1, double y1, double x2, double y2);
double circumference(double x1, double y1, double x2, double y2);
double area(double x1, double y1, double x2, double y2);
void populate_classobj(double x1, double y1, double x2, double y2);
};
#endif
这是我定义类函数的地方(circle.cc):
#include <cmath>
#include "circle.h"
#define PI (4*atan(1))
using namespace std;
double circle::distance(double x1, double y1, double x2, double y2) {
double dist;
dist = sqrt(pow((x2-x1),2)+pow((y2-y1),2));
return dist;
}
double circle::radius(double x1, double y1, double x2, double y2) {
return distance(x1, y1, x2, y2);
}
double circle::area(double x1, double y1, double x2, double y2) {
double circle_area = PI*(pow(radius(x1, y1, x2, y2),2));
return circle_area;
}
double circle::circumference (double x1, double y1, double x2, double y2) {
double circ = 2*PI*radius(x1, y1, x2, y2);
return circ;
}
void circle::populate_classobj (double x_1, double y_1, double x_2, double y_2) {
double x1 = x_1;
double y1 = y_1;
double x2 = x_2;
double y2 = y_2;
}
这是我的主要(main.cc):
#include <iostream>
#include <cmath>
#include "circle.h"
using namespace std;
int main()
{
double x_1, y_1, x_2, y_2;
int switch_val;
cout << "Enter x1 coordinate: ";
cin >> x_1;
cout << "Enter y1 coordinate: ";
cin >> y_1;
cout << "Enter x2 coordinate: ";
cin >> x_2;
cout << "Enter y2 coordinate: ";
cin >> y_2;
circle mycircle;
mycircle.populate_classobj (x_1, y_1, x_2, y_2);
do{
cout << "1 for radius, 2 for circumference, 3 for area, 4 for exit" << endl;
cout << "Enter your desired computation: ";
cin >> switch_val;
switch(1) {
case 1: cout << "Radius is: " <<endl;
cout << radius(x_1, y_1, x_2, y_2);
break;
case 2: cout << "Circumference is: " <<endl;
cout << circumference (x_1, y_1, x_2, y_2);
break;
case 3: cout << "Area is: " <<endl;
cout << area(x_1, y_1, x_2, y_2);
break;
case 4: cout << "Exiting program... "<< endl;
break;
default: cout << "Invalid input please re-input value"<<endl;
break;
}
}while(switch_val != 4);
return 0;
}
我认为这与我的#include
陈述有关,但我不确定。谢谢!
答案 0 :(得分:2)
在switch
中,您确实使用了课程circle
的方法,例如radius
。类的功能(所谓的方法)仅可用于使用该类的现有实例进行调用。
E.g。
circle mycircle;
double radius = mycircle.radius(1.0,2.0,3.0,4.0);
会奏效。
但是如果方法不需要该类的任何成员变量,则可以将其声明为static
。只需在标题中的函数前写下单词:
`static double radius(double x1, double y1, double x2, double y2);`
现在您可以在没有circle
的实例的情况下调用它。
double radius = circle::radius(1.0,2.0,3.0,4.0);
您只需使用classes命名空间,让编译器知道函数的来源。