c++ - 如何在 C++ 中转发类的声明?

标签 c++ compiler-errors forward-declaration

为什么 A 类和 B 类的前向声明不起作用?

#include <iostream>
using namespace std;

class A, B;    

class A {
public:
    A() {
        new B();
    }
};

class B {
public:
    B() {
        new A();
    }
};

int main () {
    A a = new A();
    B b = new B();
};

编译器错误:

classes.cpp:4:8: error: expected unqualified-id before ‘,’ token
classes.cpp:4:10: error: aggregate ‘A B’ has incomplete type and cannot be defined
classes.cpp: In constructor ‘A::A()’:
classes.cpp:9:7: error: expected type-specifier before ‘B’
classes.cpp:9:7: error: expected ‘;’ before ‘B’
classes.cpp: In function ‘int main()’:
classes.cpp:22:14: error: conversion from ‘A*’ to non-scalar type ‘A’ requested
classes.cpp:23:4: error: expected ‘;’ before ‘b’

最佳答案

像这样:

class A
{
public:
    A();
};

class B
{
public:
    B();
};

A::A() { new B(); }    // terrible code, leaks, serves no purpose
B::B() { new A(); }    // likewise

关于c++ - 如何在 C++ 中转发类的声明?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15747480/

相关文章:

c++ - 为什么 return 之后的语句会改变返回值?

c - 未找到 MinGW 的 SDL

c++ - 我在理解 [basic.scope.pdecl]/7 时遇到一些困难

c++ - std::exception.what() 在 clang 和 gcc 上返回意外值,但在 VS11 上不返回

android - "ndk-build finish with non-zero exit value 2"编译 textfairy 项目时

scala - 为什么Scala编译不允许作用域方法重载?

compilation - 获取 WebStorm 中依赖的 TypeScript 文件的编译错误

c++ - 结构的无效前向声明

c++ - 包含命名空间的类模板的前向声明导致编译错误

c++ - 为浮点常量调用伪析构函数的有效语法