gpt4 book ai didi

c++ - 前向声明,不完整类型

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

我得到了

Incomplete type is not allowed

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

代码如下:

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();
}

酒吧.h:

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

int getVal();
};

酒吧.cpp:

#include "Bar.h"

Bar::Bar() {}

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

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

最佳答案

包含在文件 Foo.cpp header 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;

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

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

关于c++ - 前向声明,不完整类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31898777/

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