问题描述
我正在尝试调用Triangle方法,但是我似乎在主体中没有正确地执行它。在第16行上,我有3个错误:
三角形:未声明的标识符,语法错误缺少“;”之前 标识符'newTriangle'和newTriangle未声明的标识符
第17行显示未声明的newTriangle标识符,第18行显示未声明的newTriangle标识符。
我不确定自己做错了什么或遗漏了什么。
我的代码:
#include <iostream>
#include <cmath>
using namespace std;
//Base Class (Abstract/Interface)
class Interface{
public:
virtual int area() = 0;
virtual int perimeter() = 0;
};
int main() {
Triangle newTriangle;
newTriangle.area();
newTriangle.perimeter();
};
//Triangle
class Triangle : public Interface {
int s1 = 3;
int s2 = 5;
public:
int area() {
double a = ((s1 * s2) * 1 / 2);
cout << "The area of the triangle:";
cout << a << endl;
}
int perimeter() {
double b = (s1 + s2 + s2);
cout << "The perimeter of the triangle is: ";
cout << b << endl;
}
};
解决方法
您可以这样编写代码:
#include <iostream>
#include <cmath>
using namespace std;
//Base Class (Abstract/Interface)
class Interface{
public:
virtual void area() = 0;
virtual void perimeter() = 0;
};
class Triangle : public Interface {
private:
int s1,s2;
public:
void get(int a,int b)
{
s1=a;
s2=b;
}
void area() {
double a = ((s1 * s2) * 1 / 2);
cout << "The area of the triangle:";
cout << a << endl;
}
void perimeter() {
double b = (s1 + s2 + s2);
cout << "The perimeter of the triangle is: ";
cout << b << endl;
}
};
int main() {
Triangle newTriangle;
newTriangle.get(3,5);
newTriangle.area();
newTriangle.perimeter();
}