c++ - 尝试使用 main 运行类时出错

标签 c++ std iostream program-entry-point

这是代码:

#include <iostream>
using namespace std;
class A;

int main(){
    A aObject;
    aObject.cool();
    return 0;
}
class A{
    public:
        void cool(){
            cout << "hi";
        }
 };

但是当我尝试运行它时,出现了这个错误:

||=== Build: Debug in First (compiler: GNU GCC Compiler) ===| In function 'int main()':|

error: aggregate 'A aObject' has incomplete type and cannot be defined|

||=== Build failed: 1 error(s), 0 warning(s) (0 minute(s), 0 second(s)) ===|

帮助!

最佳答案

#include <iostream>
using namespace std;
class A;

int main(){
    A aObject;

此时,编译器只知道有一个名为A的类。它还不知道关于它的任何其他信息。它不知道自己的大小,也不知道如何构造类的对象。它需要它的定义来构造一个对象。

下面的程序之所以有效,是因为编译器在您创建类的对象时就知道该类的定义:

#include <iostream>
using namespace std;

class A{
    public:
        void cool(){
            cout << "hi";
        }
 };

int main(){
    A aObject;
    aObject.cool();
    return 0;
}

关于c++ - 尝试使用 main 运行类时出错,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29050226/

相关文章:

c++ - 用 OpenGL 绘制三角形 : how to manage with two classes

c++ - 如何封装两个流缓冲区

c++ - 如果我重新定义 sqrt 函数,为什么使用 std::sqrt 会失败?

c++ - 有效使用C++ iomanip库

c++ - 有人真的使用流提取运算符吗?

c++ - 上传我的代码的最简单方法?

c++ - OpenCV中图像矩阵的子区域

C++ Winsock 下载文件切断 HTTP header

c++ - 使用 constexpr 在编译时初始化指向成员函数的指针数组

c++ - 为什么从 C++ I/O 系统中删除了 iostream_withassign、ostream_withassign 和 istream_withassign 类?