mrl*_*lux 5 c++ pointers this member parameter-passing
我是C++的新手,但我确实有一些Java经验.编码时,我偶然发现了一个让我感到困惑的错误.这是我的代码(简化,但错误是相同的):
啊:
#pragma once
#include "B.h"
class A
{
public:
A();
void foo();
void sayHello();
B b;
};
Run Code Online (Sandbox Code Playgroud)
A.cpp:
#include "A.h"
#include <iostream>
A::A() {}
void A::foo() {
b.bar(this);
}
void A::sayHello() {
std::cout << "Hello" << std::endl;
}
Run Code Online (Sandbox Code Playgroud)
BH:
#pragma once
#include "A.h"
class B
{
public:
B();
void bar(A *a);
};
Run Code Online (Sandbox Code Playgroud)
B.cpp:
#include "B.h"
B::B(){}
void B::bar(A *a) {
a->sayHello();
}
Run Code Online (Sandbox Code Playgroud)
我想了一个指针传递一个对象到酒吧在功能上乙,这样我就可以修改并访问一个在的领域吧.奇怪的是,当我通过另一个类的A实例调用foo时,我得到了这些错误:
1>------ Build started: Project: Test, Configuration: Debug Win32 ------
1> main.cpp
1>d:\stuff\visual studio 2015\projects\test\test\b.h(7): error C2061: syntax error: identifier 'A'
1> B.cpp
1>d:\stuff\visual studio 2015\projects\test\test\a.h(9): error C3646: 'b': unknown override specifier
1>d:\stuff\visual studio 2015\projects\test\test\a.h(9): error C4430: missing type specifier - int assumed. Note: C++ does not support default-int
1> A.cpp
1>d:\stuff\visual studio 2015\projects\test\test\b.h(7): error C2061: syntax error: identifier 'A'
1>d:\stuff\visual studio 2015\projects\test\test\a.cpp(5): error C2660: 'B::bar': function does not take 1 arguments
1> Generating Code...
========== Build: 0 succeeded, 1 failed, 0 up-to-date, 0 skipped ==========
Run Code Online (Sandbox Code Playgroud)
如果我不包括代码工作正常啊在了Bh和我没有通过任何的酒吧功能.
我试图google什么可能导致这些错误,但我无法自己解决问题,因为我不明白是什么导致这些错误.我究竟做错了什么?
在Ah的头文件中,您有:
#include "B.h"
Run Code Online (Sandbox Code Playgroud)
在Bh的头文件中,您有:
#include "A.h"
Run Code Online (Sandbox Code Playgroud)
A您有一个循环包含,其中和的定义B相互依赖。
一个简单的解决方案是在 的定义中使用前向声明class B:
#include "A.h"将文件Bh中的行替换为class B;#include "A.h"开头添加但请注意,您不能使用 的前向声明class A,原因是您有b的值class B作为 的成员变量class A:
#pragma once
#include "B.h"
class A
{
public:
A();
void foo();
void sayHello();
B b; /// I mean this line here more specifically
};
Run Code Online (Sandbox Code Playgroud)
编译器需要知道 的定义class B才能确定 A 类的正确大小。这就是为什么必须将 放在Ah#include "B.h"的最开头。
| 归档时间: |
|
| 查看次数: |
1761 次 |
| 最近记录: |