Jon*_*han 2 c++ variables scope class elaboration
在C ++中声明类指针变量时,何时以及为什么我们应该使用'struct'关键字?
我已经在嵌入式环境中看到了这一点,所以我怀疑这是C的一种保留。我已经看到了很多有关在声明struct对象时何时使用'struct'关键字的解释,因为它与C中的名称空间相关(在这里),但是我找不到任何人在谈论为什么在声明类指针变量时可能会使用它。
例如,在CFoo.h中:
class CFoo
{
public:
int doStuff();
};
inline Foo::doStuff()
{
return 7;
}
Run Code Online (Sandbox Code Playgroud)
后来在另一个类中:
void CBar::interesting()
{
struct CFoo *pCFoo;
// Go on to do something interesting with pCFoo...
}
Run Code Online (Sandbox Code Playgroud)
这样做的理由很少:这是C语言的失败,在这种情况下,程序员只是多愁善感-也许是为了追求可读性。就是说,它可以代替前向声明。
在某些情况下,您可能需要消除歧义,但事实并非如此。需要消除歧义的一个例子是
class foo{};
int main()
{
int foo;
class foo* pf1;
struct foo* pf2;
}
Run Code Online (Sandbox Code Playgroud)
请注意,您可以使用class和struct互换。您也可以使用typename,这在使用模板时很重要。以下是有效的C ++:
class foo{};
int main()
{
class foo* pf1;
struct foo* pf2;
typename foo* pf3;
}
Run Code Online (Sandbox Code Playgroud)
这样做有两个原因。
第一个是如果我们要使用详细的名称在作用域中引入新类型。在这个定义中
void CBar::interesting()
{
struct CFoo *pCFoo;
// Go on to do something interesting with pCFoo...
}
Run Code Online (Sandbox Code Playgroud)
如果struct CFoo尚未声明,则在范围内引入新类型。指针可能指向不完整的类型,因为指针本身是完整的类型。
第二个是类的名称被函数或变量的声明隐藏时。在这种情况下,我们再次需要使用详细的类型名称。
这里有些例子
#include <iostream>
void CFoo( const class CFoo * c ) { std::cout << ( const void * )c << '\n'; }
class CFoo
{
public:
int doStuff();
};
int main()
{
class CFoo c1;
return 0;
}
Run Code Online (Sandbox Code Playgroud)
要么
#include <iostream>
class CFoo
{
public:
int doStuff();
};
void CFoo( void ) { std::cout << "I am hidding the class CGoo!\n"; }
int main()
{
class CFoo c1;
return 0;
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
118 次 |
| 最近记录: |