C++主函数后声明类是否可行?

5
#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函数前使用class Calculator;,但它没有起作用。
3个回答

6

你不能按照你写的那样做。编译器必须在使用类之前看到类的定义。你需要将类放在main函数之前,或者更好的方法是将其放在一个单独的头文件中,然后再进行包含。


1
为什么函数不是这种情况呢? - Anthony Raimondo
1
这是因为编译器在定义函数之前无法使用它。不同之处在于,函数的主体可以放置在任何位置,因为链接器会解析您正在调用的实际代码所在的位置。但编译器仍然必须知道函数定义的样子。 - Jonathan Potter

6
在预声明后,您可以针对计算器创建指针。问题在于构造函数(new Calculator())此时还没有被定义。您可以这样做:
在主函数之前:
class Calculator { // defines the class in advance
public:
    Calculator(); // defines the constructor in advance
    ~Calculator(); // defines the destructor in advance
};

在 main 函数之后:
Calculator::Calculator(){ // now implement the constructor
}
Calculator::~Calculator(){ // and destructor
}

1
在main函数之前放置类定义:
#include "stdafx.h"
using namespace System;

class Calculater
{
public:
    Calculater()
    {
    }
    ~Calculater()
    {
    }

};

int main(array<System::String ^> ^args)
{
    Calculater *calculater = new Calculater();

    return 0;
}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接