c++ - 如何在 C++ 中使用类原型(prototype)

标签 c++ class prototype

我试图在定义类之前创建类对象。这是示例。

class A;
class B;

class A{
    public: 
    void fun(B obj){
    }
};
class B{ };
int main(){

    return 0;
}

这是错误列表:

In member function 'void A::fun(B)':
6   13  [Error] 'obj' has incomplete type
2   7   [Error] forward declaration of 'class B'

有什么解决办法吗?我已经搜索过它,但未能解决这个问题.. 提前致谢。

最佳答案

B 完全声明后,提供 A::fun() 的定义:

#include <iostream>

class A;
class B;

class A {
    public: 
    void fun(B obj);
};

class B{ };

void A::fun(B obj) {}

int main() {
    return 0;
}

定义通常会放入 .cpp 文件中,您可以在其中包含 B.h 以获得完整的声明。

此外,please don't using namespace std; .

关于c++ - 如何在 C++ 中使用类原型(prototype),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32053699/

相关文章:

c++ - 在不定义所有宏的情况下使用 cppcheck

c++ - 下一个更大的元素

jquery - 获取 ul 的当前事件类

Java:LinkedList 类作为堆栈和队列

在 header 中没有声明的调用函数

javascript - 删除属性显示为 :none via Javascript 的页面上的 div

c++ - 继承在 child 中初始化的数组

c++ - 如何在 C++ 和 GLSL 之间打包(4 字节)和解包(vec4)

PHP 类名冲突

javascript - 来自 : "Javascript - The Good Parts" 的示例