【问题标题】:forward declarations, Incomplete type前向声明,不完整类型
【发布时间】:2015-08-08 21:29:52
【问题描述】:

我收到了

不允许不完整的类型

错误。显然我不明白前向声明是如何工作的。我知道我不能在头文件中使用方法,但是在实现中呢?

代码如下:

Foo.h:

#pragma once

class Bar;

class Foo {
    const Bar &mBar;

public:
    Foo(const Bar &bar);

    int getVal() const;
};

Foo.cpp:

#include "Foo.h"

Foo::Foo(const Bar &bar) : mBar(bar) {}

int Foo::getVal() const {
    return mBar.getVal();
}

Bar.h:

#pragma once
class Bar {
public:
    Bar();

    int getVal();
};

Bar.cpp:

#include "Bar.h"

Bar::Bar() {}

int Bar::getVal() {
    return 5;
}

mBar.getVal() 是导致错误的原因。但是它在实现文件中。这也不允许吗?

【问题讨论】:

    标签: c++


    【解决方案1】:

    包含在文件中Foo.cpp 标头Bar.h

    Foo.cpp:

    #include "Foo.h"
    #include "Bar.h"
    
    Foo::Foo(const Bar &bar) : mBar(bar) {}
    
    int Foo::getVal() const {
        return mBar.getVal();
    }
    

    或者在标题Foo.h中包含标题Bar.h

    Foo.h:

    #pragma once
    #include "Bar.h"
    
    class Foo {
        const Bar &mBar;
    
    public:
        Foo(const Bar &bar);
    
        int getVal() const;
    };
    

    考虑到函数 Bar::getVal 必须有限定符 const

    int getVal() const;
    

    否则你会得到一个更多的编译错误,因为这个非常量函数是从 Foo 类的 const 函数调用的。

    int Foo::getVal() const {
        return mBar.getVal();
        //     ^^^^^^^^^^^ 
    }
    

    【讨论】:

      【解决方案2】:

      从编译器的角度思考。当它在编译源文件Foo.cpp 并来到声明mBar.getVal() 时,它不知道mBar 的成员!它只知道 mBar 是对 const Bar 对象的引用。但是如果不让 Bar 类定义对编译器可见,您将无法访问它的成员。

      通常,您在头文件中进行前向声明以避免引入过多的头文件(如果头文件是外部可见 API 的一部分,这一点很重要)。在源文件中,您应该包含包含类定义的头文件;在这种情况下Bar.h

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2017-06-18
        • 1970-01-01
        • 1970-01-01
        • 2011-10-22
        • 2013-07-09
        • 1970-01-01
        • 1970-01-01
        • 2017-11-07
        相关资源
        最近更新 更多