main后的类声明

c++ Class declaration after main?

本文关键字:声明 main      更新时间:2023-10-16
#include "stdafx.h"
using namespace System;
class Calculater; // how to tell the compiler that the class is down there? 
int main(array<System::String ^> ^args)
{
    ::Calculater *calculater = new Calculater();
    return 0;
}
class Calculater
{
public:
    Calculater()
    {
    }
    ~Calculater()
    {
    }
};

我在main之后声明类,我如何告诉编译器我的类是?我试着
类计算机;在main之前,但它不起作用。

你不能按照你写的去做。编译器在使用类之前必须能够看到类的定义。您需要将类放在main函数之前,或者最好放在单独的头文件中,其中包括

您可以在预声明之后使用指向Calculator的指针。问题是构造函数(new Calculator()),它在那时还没有定义。你可以这样做:

主要前

:

class Calculator { // defines the class in advance
public:
    Calculator(); // defines the constructor in advance
    ~Calculator(); // defines the destructor in advance
};
主后

:

Calculator::Calculator(){ // now implement the constructor
}
Calculator::~Calculator(){ // and destructor
}

把类定义放在main前面:

#include "stdafx.h"
using namespace System;
class Calculater
{
public:
    Calculater()
    {
    }
    ~Calculater()
    {
    }
};
int main(array<System::String ^> ^args)
{
    Calculater *calculater = new Calculater();
    return 0;
}