Can I avoid using the class name in the .cpp file if I declare a namespace in the header? [duplicate]

半腔热情 提交于 2021-02-07 12:48:48

问题


In C++, all I want to do is declare a DisplayInfo class in a .h file, and then in the .cpp file, not have to type the first DisplayInfo::DisplayInfo() and every function definition.

Sadly, I've looked at over 20 topics and my C++ book for over two hours now and have not been able to resolve this. I think it's because I'm trying to use my 10-year-old java training in C++.

1st trial:

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

For the second trial, I tried switching the order, so it was

class DisplayInfo
{

  namespace DisplayInfoNamespace
  {
  ...
  }
}

And in the .cpp file, tried all of the above plus

using namespace DisplayInfo::DisplayInfoNamespace; 

For the third trial I tried forward declaring it with this header:

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

I'm using VisualStudio2010 express and despite carefully reading the error messages have not been able to find the right arrangement of classes and namespaces in the header and .cpp file to make this work out.

And now after I spent 30 minutes typing this, is C++: "Class namespaces"? the answer? (aka no, you have to use typedefs?)


回答1:


There is no way to shorten the A::A() definition syntax, when you do it outside of the class.

within the class it would alow you to define the functions inplace without havinf to select the correct scope.

example:

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

As you can see, namespaces would rather add another thing to put in front of your method name, rather than remove one.



来源:https://stackoverflow.com/questions/15827985/can-i-avoid-using-the-class-name-in-the-cpp-file-if-i-declare-a-namespace-in-th

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!