【问题标题】:Forward Declaration of Classes in C++C++ 中类的前向声明
【发布时间】:2015-12-04 01:17:47
【问题描述】:

我编写了以下代码,我将通过它来帮助我查看继承以及调度/双重调度在 C++ 中的工作原理,但它不会编译。我查看了类原型/前向声明,我已经完成了,但我仍然收到错误“B 是不完整的类型”、“SubB 是不完整的类型”等。有什么问题?

#include <iostream>

class B;
class SubB;

class A { 
    public:
        void talkTo(B b){
            std::cout << "A talking to instance of B" << std::endl;
        }
        void talkTo(SubB sb){
            std::cout << "A talking to instance of SubB" << std::endl;
        }
};
class SubA : A {
    public:
        void talkTo(B b){
            std::cout << "SubA talking to instance of B" << std::endl;
        }
        void talkTo(SubB sb){
            std::cout << "SubA talking to instance of SubB" << std::endl;
        }
};
class B { 
    public:
        void talkTo(A a){
            std::cout << "B talking to instance of A" << std::endl;
        }
        void talkTo(SubA sa){
            std::cout << "B talking to instance of SubA" << std::endl;
        }
};
class SubB : B {
    public:
        void talkTo(A a){
            std::cout << "SubB talking to instance of A" << std::endl;
        }
        void talkTo(SubA sa){
            std::cout << "SubB talking to instance of SubA" << std::endl;
        }
};

编辑

将参数更改为引用使这项工作(来自 R Sahu 的帮助)但为什么现在不工作?

class A { 
    public:
        void talkTo(B &b){
            //std::cout << "A talking to instance of B" << std::endl;
            b.talkTo(this);
        }
        void talkTo(SubB &sb){
            //std::cout << "A talking to instance of SubB" << std::endl;
            sb.talkTo(this);
        }
};
class B { 
    public:
        void talkTo(A &a){
            std::cout << "B talking to instance of A" << std::endl;
        }
        void talkTo(SubA &sa){
            std::cout << "B talking to instance of SubA" << std::endl;
        }
};
class SubB : B {
    public:
        void talkTo(A &a){
            std::cout << "SubB talking to instance of A" << std::endl;
        }
        void talkTo(SubA &sa){
            std::cout << "SubB talking to instance of SubA" << std::endl;
        }
};

A a;
SubA subA;
B b;
SubB subB;

a.talkTo(b);
a.talkTo(subB);

【问题讨论】:

  • 你可能还是想使用传递引用,除非你不想和任何人交谈!
  • 是的,在一个真正的实现中是肯定的,但我只是为了看看是什么类型通过我没有传递任何类型的数据

标签: c++ oop inheritance forward-declaration


【解决方案1】:

当你有一个前向声明时,你可以使用只作为引用的类型:指针和引用是最明显的引用。

而不是

    void talkTo(B b){
        std::cout << "A talking to instance of B" << std::endl;
    }
    void talkTo(SubB sb){
        std::cout << "A talking to instance of SubB" << std::endl;
    }

使用

    void talkTo(B const& b){
        std::cout << "A talking to instance of B" << std::endl;
    }
    void talkTo(SubB const& sb){
        std::cout << "A talking to instance of SubB" << std::endl;
    }

【讨论】:

  • 您不能使用前向声明进行函数调用。如果需要进行函数调用,则必须移动函数的实现。它需要在类定义之外和类定义之后实现。在您的情况下,它们需要在类 BSubB 的定义之后实现。
猜你喜欢
  • 2021-12-25
  • 1970-01-01
  • 2023-03-16
  • 2011-07-08
  • 2013-06-02
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多