第16、17和18行的C ++未声明标识符

问题描述

我正在尝试调用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();

}

相关问答

Selenium Web驱动程序和Java。元素在(x,y)点处不可单击。其...
Python-如何使用点“。” 访问字典成员?
Java 字符串是不可变的。到底是什么意思?
Java中的“ final”关键字如何工作?(我仍然可以修改对象。...
“loop:”在Java代码中。这是什么,为什么要编译?
java.lang.ClassNotFoundException:sun.jdbc.odbc.JdbcOdbc...