在C++中通常用某种前缀命名成员变量来表示它们是成员变量而不是局部变量或参数.如果你来自MFC背景,你可能会使用m_foo.我myFoo偶尔也见过.
C#(或者可能只是.NET)似乎建议只使用下划线,如_foo.这是否允许C++标准?
我经常发现自己处于一种情况,我在C++项目中面临多个编译/链接器错误,因为一些糟糕的设计决策(由其他人做出:))导致不同头文件中C++类之间的循环依赖(也可能发生)在同一个文件中).但幸运的是(?)这种情况经常不足以让我在下次再次发生问题时记住这个问题的解决方案.
因此,为了便于将来回忆,我将发布一个代表性问题和解决方案.更好的解决方案当然是受欢迎的.
A.h
class B;
class A
{
int _val;
B *_b;
public:
A(int val)
:_val(val)
{
}
void SetB(B *b)
{
_b = b;
_b->Print(); // COMPILER ERROR: C2027: use of undefined type 'B'
}
void Print()
{
cout<<"Type:A val="<<_val<<endl;
}
};
Run Code Online (Sandbox Code Playgroud)B.h
#include "A.h"
class B
{
double _val;
A* _a;
public:
B(double val)
:_val(val)
{
}
void SetA(A *a)
{
_a = a;
_a->Print();
}
void Print()
{
cout<<"Type:B val="<<_val<<endl;
}
};
Run Code Online (Sandbox Code Playgroud)main.cpp
#include "B.h" …Run Code Online (Sandbox Code Playgroud)我确定之前已经问过这个问题,但我似乎无法找到它.
我有两节课,Vector和Point.
这些文件是这样的(有点重复):
vector.h:
#include <math.h>
#include <stdlib.h>
class Vector {
friend class Point;
public:
...
Vector(Point); // Line 16
Run Code Online (Sandbox Code Playgroud)
vector.cpp:
#include <math.h>
#include <stdlib.h>
#include "vector.h"
...
Vector::Vector(Point point) { // Line 29
x = point.x;
y = point.y;
z = point.z;
}
Run Code Online (Sandbox Code Playgroud)
point.cpp并且point.h看起来几乎相同,除了你换vector用point的定义.
我把它们包括在内:
#include "structures/vector.cpp"
#include "structures/point.cpp"
Run Code Online (Sandbox Code Playgroud)
当我编译时,我收到此错误:
structures/vector.h:16:17: error: field ‘Point’ has incomplete type
structures/vector.cpp:29:15: error: expected constructor, destructor, or type conversion before …Run Code Online (Sandbox Code Playgroud)