c++ 在成员函数中用作参数时,前向声明不起作用

s4n0splo  于 2024-01-09  发布在  其他
关注(0)|答案(1)|浏览(207)

我在类A之前对class B;的前向声明在下面的代码中不起作用,即使this answer提到在函数的参数中使用不完整类型的前向声明时也应该起作用。
它在A::func()中抛出一个错误,说“未定义类型B”。对此应该如何修复?为什么我的前向声明在这种情况下不起作用?
代码

  1. #include <iostream>
  2. using namespace std;
  3. class B;
  4. class A
  5. {
  6. public:
  7. A()
  8. {
  9. cout << "in A's default ctor" << endl;
  10. }
  11. void func(B b1)
  12. {
  13. cout << "in A's func" << endl;
  14. }
  15. private:
  16. int x;
  17. };
  18. class B
  19. {
  20. public:
  21. B()
  22. {
  23. cout << "in B's default ctor" << endl;
  24. }
  25. B(const B& b1)
  26. {
  27. cout << "in B's copy ctor" << endl;
  28. }
  29. B& operator=(const B& b1)
  30. {
  31. cout << "in B's copy assignment operator" << endl;
  32. return *this;
  33. }
  34. };
  35. int main()
  36. {
  37. A a;
  38. B b;
  39. a.func(b);
  40. }

字符串

ars1skjm

ars1skjm1#

来自C++17标准(6.2单定义规则,第5页)
一个类类型T必须是完整的,如果
(5.9)- 返回类型或参数类型为T的函数被定义(6.1)或调用(8.2.2),或者
为了避免这个错误,在类B的定义之后,在类A之外定义成员函数func

  1. class B;
  2. class A
  3. {
  4. public:
  5. //...
  6. void func(B b1);
  7. //...
  8. };
  9. class B
  10. {
  11. //...
  12. };
  13. void A::func(B b1)
  14. {
  15. cout << "in A's func" << endl;
  16. }

字符串
或者没有forward声明,

  1. class A
  2. {
  3. public:
  4. //...
  5. void func(class B b1);
  6. //...
  7. };
  8. class B
  9. {
  10. //...
  11. };
  12. void A::func(B b1)
  13. {
  14. cout << "in A's func" << endl;
  15. }

展开查看全部

相关问题