gpt4 book ai didi

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

转载 作者:太空狗 更新时间:2023-10-29 20:14:39 25 4
gpt4 key购买 nike

为什么 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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com