开发者

How to create an object of class defined inside namespace in c++

开发者 https://www.devze.com 2023-04-03 23:48 出处:网络
namespace t { class A {}; } How can create an object of class A? EDIT : namespace beta { class TESSDLL_API TessB开发者_如何学运维aseAPI
namespace t {
    class A {};
}

How can create an object of class A?

EDIT :

namespace beta {
  class TESSDLL_API TessB开发者_如何学运维aseAPI 
  { 
     public: 
           TessBaseAPI(); 
           virtual ~TessBaseAPI(); 
  }
}

This is the class defined inside beta  namespace . Now how do i call the constructor? is

tess = new beta::TessBaseAPI(); 

correct?


As you would normally do. The only difference is that A is inside the namespace t. So you can :

use the scope resolution operator every time you want to use A :

t::A a;

use the using directive

using namespace t; 
A a;

or, as Luc Danton pointed out use the using declaration

using t::A;
A a;

following your edit :

Assuming that your class declaration is ending with a ; as in

namespace beta {
  class TESSDLL_API TessBaseAPI 
  { 
     public: 
           TessBaseAPI(); 
           virtual ~TessBaseAPI(); 
  };
}

Then the correct way to call the constructor is :

beta::TessBaseAPI * tess = beta::TessBaseAPI();

or

beta::TessBaseAPI tess;


Either

namespace t
{
    A a;
}

or

t::A a;

In the first case a lives inside namespace t (in fact its full name is ::t::a). In the second case a is global.

(note: your class A{} is missing a ; after })


namespace t
{
    class A {} a;
    A another_a;
}

Now use t::a or t::another_a.

If you want to make another object:

t::A another_a_out_of_namespace_scope;


Use a semicolon after the declaration of the class, and use:

t::A my_object;

muntoo's answer allows you to create a single instance of the class and is also correct.


For an object named x;

t::A x;
0

精彩评论

暂无评论...
验证码 换一张
取 消