use*_*872 6 c++ namespaces class definition
在C++中,我想要做的就是DisplayInfo在.h文件中声明一个类,然后在.cpp文件中,不必键入第一个DisplayInfo::DisplayInfo()和每个函数定义.
可悲的是,我已经看了20多个主题和我的C++书,现在已经超过两个小时了,但却无法解决这个问题.我认为这是因为我正在尝试使用我在C++中进行的10年历史的java训练.
第一次试用:
//DisplayInfo.h
namespace DisplayInfoNamespace
{
Class DisplayInfo
{
public:
DisplayInfo(); //default constructor
float getWidth();
float getHeight();
...
};
}
//DisplayInfo.cpp
using namespace DisplayInfoNamespace; //doesn't work
using namespace DisplayInfoNamespace::DisplayInfo //doesn't work either
using DisplayInfoNamespace::DisplayInfo //doesn't work
{
DisplayInfo::DisplayInfo() {}; //works when I remove the namespace, but the first DisplayInfo:: is what I don't want to type
DisplayInfo::getWidth() {return DisplayInfo::width;} //more DisplayInfo:: that I don't want to type
...
}
Run Code Online (Sandbox Code Playgroud)
对于第二次试验,我尝试切换订单,所以它是
class DisplayInfo
{
namespace DisplayInfoNamespace
{
...
}
}
Run Code Online (Sandbox Code Playgroud)
并在.cpp文件中,尝试了以上所有加号
using namespace DisplayInfo::DisplayInfoNamespace;
Run Code Online (Sandbox Code Playgroud)
对于第三次试验,我尝试使用此标题声明它:
namespace DisplayInfoNamespace
{
class DisplayInfo;
}
class DisplayInfo
{
public:
...all my methods and constructors...
};
Run Code Online (Sandbox Code Playgroud)
我正在使用VisualStudio2010 express,尽管仔细阅读错误消息仍无法在头文件和.cpp文件中找到正确的类和命名空间排列,以使这项工作成功.
现在,在我花了30分钟打字之后,是C++:"类名称空间"?答案?(又名不,你必须使用typedef?)
A::A()当您在类之外执行定义语法时,无法缩短定义语法。
在类中,它允许您就地定义函数,而无需选择正确的范围。
例子:
// in *.h
namespace meh {
class A {
public:
A() {
std::cout << "A construct" << std::endl;
}
void foo();
void bar();
}
void foo();
}
void foo();
// in *.cpp
void foo() {
std::cout << "foo from outside the namespace" << std::endl;
}
void meh::foo() {
std::cout << "foo from inside the namespace, but not inside the class" << std::endl;
}
void meh::A::foo() {
std::cout << "foo" << std::endl;
}
namespace meh {
void A::bar() {
std::cout << "bar" << std::endl;
}
}
Run Code Online (Sandbox Code Playgroud)
正如您所看到的,命名空间宁愿在方法名称前面添加另一件事,而不是删除一个。