7

在 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
  ...
}

第二次试用,我尝试切换顺序,结果是

class DisplayInfo
{

  namespace DisplayInfoNamespace
  {
  ...
  }
}

.cpp文件中,尝试了以上所有加

using namespace DisplayInfo::DisplayInfoNamespace; 

对于第三次试验,我尝试使用此标头向前声明它:

namespace DisplayInfoNamespace
{
  class DisplayInfo;
}
class DisplayInfo
{
public:
...all my methods and constructors...
};

我正在使用 VisualStudio2010 express,尽管仔细阅读了错误消息,但仍然无法在头文件和 .cpp 文件中找到正确的类和命名空间排列来解决这个问题。

现在,在我花了 30 分钟打字之后,是C++:“类命名空间”吗?答案?(又名不,你必须使用 typedefs 吗?)

4

1 回答 1

0

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

正如您所看到的,命名空间宁愿在您的方法名称前面添加另一个东西,而不是删除一个。

于 2013-04-05T07:22:00.170 回答