开发者

Trouble declaring object of included type

If I declare an object in my header file, I get a compilation error. I can, however, construct it in my application's setup() method, simply by calling Analyzer A(44100., "a", 200);.

If I construct it this way, how do I keep a pointer to it? Won't the object be inaccessible once the constructor call has gone out of scope?

Or, is there another way I should be getting an instance of this object?

(What I'm used to is putting something like Analyzer A; in my heade开发者_StackOverflow中文版r and then in the cpp putting A = new Analyzer(44100., "a", 200);. This, though, won't compile.)

Analyzer.hh:

class Analyzer {
  public:
    /// constructor
    Analyzer(double rate, std::string id, std::size_t step = 200);
};

Analyzer.cc:

Analyzer::Analyzer(double rate, std::string id, std::size_t step):
  m_step(step),
  m_rate(rate),
  m_id(id),
  m_window(FFT_N),
  m_bufRead(0),
  m_bufWrite(0),
  m_fftLastPhase(FFT_N / 2),
  m_peak(0.0),
  m_oldfreq(0.0)
{
/* ... */
}

testApp.h:

#include "Analyzer.hh"

class testApp : public ofSimpleApp{
public:

// *This line gives compilation error 
// "No matching function for call to Analyzer::Analyzer()"

      Analyzer A;
    }

testApp.cpp:

void testApp::setup(){

// *This line compiles, but how will I access 
//this object outside of current scope?*
  Analyzer A(44100., "a", 200);
}


you can initialize constructor type of A in constructor of testApp as

testApp:testApp():A(44100., "a", 200){
//testApp constructor. 
}


You need to learn C++ from scratch. You're trying to bring over reference semantics from a language like Java or C# and those don't exist in C++. You need a C++ approach.

Analyzer A; is a value. It is constructed directly. If you use a member variable, you must construct it with the initializer list.

testApp::testApp()
: A( args ) {}

When on function local scope, traditionally you return a copy of the object, or use a self-owning smart pointer such as shared_ptr to hold the object. In C++, you do not resort to dynamic allocation unless you actually need a dynamic lifetime- you can alias stack-based variables if you need to.


Analyzer A; -> Analyzer *A; and Analyzer A(44100., "a", 200); -> A = new Analyzer(44100., "a", 200);

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜