C ++什么代码,如果我把一个类后main()函数 [英] C++ what to code if i put a class after main() function

查看:122
本文介绍了C ++什么代码,如果我把一个类后main()函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在看一些关于C ++的视频教程,我知道你必须在使用或调用之前定义一个函数/类。但我喜欢让我的main()函数在顶部,和其他一切下面的主要功能。我知道如果我定义一个函数下面的主要功能我必须声明它之前使用它,但一个类呢?我需要将上面的主要函数放在main函数下面使用我的类。

I'm watching some video tutorials on C++ and i know you must define a function / class before it is used or called. But I like having my main() function at the top, and everything else below the main function. I know if i define a function below the main function I must declare it before it is used, but what about a class? What do I need to put above my main function to use my class below the main function.

#include <iostream>
using namespace std;

int main()
{
    ClassOne one;
    one.coolSaying();
    return 0;
}

class ClassOne
{
    public:
        void coolSaying()
        {
            cout << "Cool stuff yo!" << endl;
        }
};

我试图通过将此类放在main()之前定义我的类:

I tried defining my class by placing this right before main():

class ClassOne;

但不起作用。

推荐答案

这就是为什么头文件通常在C ++中使用的原因。当你说 ClassOne 时,编译器需要知道类是什么样子来创建该类型的对象。仅仅知道类存在于某个地方是不够的(如果你想要的只是一个指针就足够了)。因此,编译器需要已经读取了类的定义。

This is why header files are normally used in C++. When you're saying ClassOne one, the compiler needs to know what the class looks like to create an object of that type. It's not enough to know that the class exists somewhere (that is enough if all you want is a pointer). So the compiler needs to already have read the definition of the class.

您的类必须在首次使用之前进行定义。如果不在 main 之前明确显示,通常的方法是创建一个头文件。所以你用类声明创建 ClassOne.h ,你在 #includeClassOne.h 在这种情况下,类的实际方法通常在另一个源文件中, ClassOne.cpp

Your class has to be defined before it is first used. Without putting it explicitly before main, the usual way is to create a header file. So you create ClassOne.h with the class declaration, and you have #include "ClassOne.h at the top of your file. In this situation the actual methods of the class would normally be in another source file, ClassOne.cpp.

这篇关于C ++什么代码,如果我把一个类后main()函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆