【问题标题】:C++ Undeclared Identifier on Object creation对象创建上的 C++ 未声明标识符
【发布时间】:2016-04-23 04:23:18
【问题描述】:

所以我是 C++ 的新手,来自 C#。这在编译时给了我几个错误,这些错误似乎都与这个对象声明有关。任何人都可以向我展示正确的方法吗?

我在声明 tri(sideLength) 的地方得到一个未声明的标识符。

我使用this 作为对象声明的参考,但它似乎对我没有帮助。

谢谢。

#include <iostream>    // Provides cout
#include <iomanip>     // Provides setw function for setting output width
#include <cstdlib>     // Provides EXIT_SUCCESS
#include <cassert>     // Provides assert function
#include <stdexcept>
#include <math.h> 

using namespace std;   // Allows all standard library items to be used

void setup_cout_fractions(int fraction_digits)
// Precondition: fraction_digits is not negative.
// Postcondition: All double or float numbers printed to cout will now be
// rounded to the specified digits on the right of the decimal.
{
    assert(fraction_digits > 0);
    cout.precision(fraction_digits);
    cout.setf(ios::fixed, ios::floatfield);
    if (fraction_digits == 0)
        cout.unsetf(ios::showpoint);
    else
        cout.setf(ios::showpoint);
}

int main()
{
    const int MAX_SIDE_LENGTH = 6;
    const int INITIAL_LENGTH = 1;
    const int DIGITS = 4;
    const int ARRAY_SIZE = 6;

    // Set up the output for fractions and print the table headings.
    setup_cout_fractions(DIGITS);

    // Each iteration of the loop prints one line of the table.
    for (int sideLength = 0; sideLength < MAX_SIDE_LENGTH; sideLength += 1)
    {
        EquilateralTriangle tri(sideLength);
        //Square sq(sideLength);
        //Pentagon_Reg pent(sideLength);
        //Hexagon_Reg hex(sideLength);
        //Heptagon_Reg hept(sideLength);
        //Octagon_Reg octa(sideLength);

        cout << "Type: " << tri.Name() << "has area: " << tri.Area() << " with SideLength = " << sideLength;
    }

    return EXIT_SUCCESS;
}

//Template

class GeometricFigure
{
public:
    GeometricFigure() { }
    double SideLength;
    virtual double Area() { return 0; };
    virtual char* Name() { return ""; };
};

class EquilateralTriangle : public GeometricFigure {
public:
    EquilateralTriangle(double sideLength)
    {
        SideLength = sideLength;
    }
    char* Name() { return "Equilateral Triangle"; }
    double Area() { return (sqrt(3) / 2 * pow(SideLength, 2)); }
};

【问题讨论】:

  • 错误是什么。您是否尝试将您的类移到主函数之上?

标签: c++ object


【解决方案1】:

在 C++ 中,编译器从上到下读取您的代码,一次。这是早期 C 编译器只有几千字节的内存可供使用时的遗留问题 - C 的设计目的是让编译器一次只需要查看一点点代码。

因此,在您尝试使用它们之前,必须根据需要声明或定义事物。

将两个类移到main 之前的某个位置。 GeometricFigure必须在EquilateralTriangle之前,EquilateralTriangle必须在main之前。

【讨论】:

  • 谢谢!有趣的背景故事。
【解决方案2】:

您需要“声明”或告诉编译器在哪里查找 EquilateralTriangle 和 GeometricFigure,“在”您首先使用它之前。你可能想看看类似的讨论 - C# declarations vs definitions

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-11-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多