Got 2 errors in my program :"use of undeclared identifier 'front'" and "call to non-static member function without an object argument" - variables

I'm trying to call some functions from GenDList.h inside GenQueue.h after including, but I'm getting a couple errors.
This is my header, GenDList.h:
#ifndef GENDLIST_H
#define GENDLIST_H
#include <iostream>
#include "GenListNode.h"
using namespace std;
template <class T>
class GenDList
{
public:
GenListNode<T> *front;
GenListNode<T> *back;
unsigned int size;
GenDList();
~GenDList();
void insertFront(T data);
void insertBack(T data);
bool insertAfter(int key, T data);
T removeFront();
T removeBack(); //for doubly
T removeAt(int position);
int isEmpty();
unsigned int getSize();
void printList();
T find(T d);
};
#endif
This is my other header that I included the previous header file into, GenQueue.h:
#ifndef GENQUEUE_H
#define GENQUEUE_H
#include <iostream>
#include "GenDList.h"
using namespace std;
template <class T>
class GenQueue
{
public:
GenQueue();
~GenQueue();
void insert(T data);
T remove();
T peek();
int isEmpty();
int isFull();
};
#endif
//***********implementation***************
template <class T>
GenQueue<T>::GenQueue()
{
GenDList<T> list;
}
template <class T>
GenQueue<T>::~GenQueue()
{
}
template <class T>
void GenQueue<T>::insert(T data)
{
GenDList<T>::insertBack(data);
}//error: call to non-static member function without an object argument
template <class T>
T GenQueue<T>::remove()
{
GenDList<T>::removeFront();
}
template <class T>
T GenQueue<T>::peek()
{
return front; //error: use of undeclared identifier here
}

Related

Boost serialization and pointers to parent class

Assuming the following simplified code:
Parent class
#include <boost/archive/text_oarchive.hpp>
#include <boost/archive/text_iarchive.hpp>
#include <boost/serialization/unique_ptr.hpp>
class Parent
{
public:
Parent();
...
private:
// boost serialization
friend class boost::serialization::access;
template<class Archive>
void serialize(Archive & ar, const unsigned int version)
{
ar & *m_child;
}
std::unique_ptr<Child> m_child;
}
Parent::Parent()
{
...
m_child = std::unique_ptr<Child>(new Child(this));
}
Child class
#include <boost/archive/text_oarchive.hpp>
#include <boost/archive/text_iarchive.hpp>
#include <boost/serialization/unique_ptr.hpp>
class Child
{
public:
Child(Parent * parent)
{
m_parent = parent;
};
...
private:
// boost serialization
friend class boost::serialization::access;
template<class Archive>
void serialize(Archive & ar, const unsigned int version)
{
ar & m_parent;
}
Child(){};
Parent m_parent{ nullptr };
}
My parent class creates a child class and passes a pointer to itself stored by the child.
When archiving the parent class, it archives the child which archives the pointer to the parent.
When restoring the parent class, it creates the child class and restores it as well. My question is this:
Will the pointer in the child class get restore properly so it is guaranteed to point to it's parent?
This SEEMS to work which I've verified by stepping through the debugger and comparing the values of the Parent's this pointer with the child's m_parent. However, I can't figure out how boost pulls this off and it makes me wonder if I'm just 'getting lucky'. Can anyone verify that boost serialization is smart enough to maintain the child::m_parent->parent relationship?
Or should I be taking the extra step of not archiving the pointer and setting it after loading the object?
Two things:
Object Tracking facilitates this. Object Tracking is enabled by default when serializing pointers.
No, you do not serialize the unique_ptr like that.
In fact, there's little reason to serialize the m_parent of the child, either, because the parent can set the self-reference from within the load handler.
But assuming that you want the easy way, let's stick with that idea and make it work due to Object Tracking
DEMO
I included some tricks to demonstrate that deserialization
correct de-duplicates pointers to the same object
restores the member pointers even if we forcefully "break" the invariants prior to deserialization
Live On Coliru
#include <boost/archive/text_iarchive.hpp>
#include <boost/archive/text_oarchive.hpp>
#include <boost/serialization/unique_ptr.hpp>
#include <memory>
#include <sstream>
#include <iostream>
class Parent;
class Child {
public:
Child(Parent *parent)
: m_parent(parent), m_duplicate_parent(parent) {}
Parent *m_parent { nullptr };
Parent *m_duplicate_parent{ nullptr };
private:
friend class boost::serialization::access;
template <class Archive> void serialize(Archive &ar, unsigned) {
ar & m_parent & m_duplicate_parent;
}
Child() = default;
};
class Parent {
public:
Parent() : m_child(std::make_unique<Child>(this)) {}
//private:
friend class boost::serialization::access;
template <class Archive> void serialize(Archive &ar, unsigned) {
ar & m_child;
}
std::unique_ptr<Child> m_child;
};
int main() {
std::stringstream ss;
{
boost::archive::text_oarchive oa(ss);
Parent p;
assert(&p == p.m_child->m_parent);
assert(&p == p.m_child->m_duplicate_parent);
oa << p;
}
std::cout << ss.str();
{
boost::archive::text_iarchive ia(ss);
Parent p;
// let's purposelly break the invariants so we know deserialization
// does restore them as required, and we not just "getting lucky":
p.m_child->m_parent = nullptr;
p.m_child->m_duplicate_parent = nullptr;
assert(&p != p.m_child->m_parent);
assert(&p != p.m_child->m_duplicate_parent);
// nuclear:
p.m_child.reset();
// now deserialize
ia >> p;
assert(&p == p.m_child->m_parent);
assert(&p == p.m_child->m_duplicate_parent);
}
}
Prints something similar to
22 serialization::archive 15 1 0
0 0 0 2 1 0
1 0 0 0 0

How to serialize std::chrono::duration with Boost?

Is it possible to serialize std::chrono::duration or especially std::chrono::milliseconds with boost::serialization?
The following error occurred:
"struct std::chrono::duration >’ has no member named ‘serialize"
I need this for my template-class:
#include <iostream>
#include <chrono>
#include <boost/serialization/serialization.hpp>
template<typename T>
class Field {
public:
// Default Constructor
Field() {}
Field(std::string name, T value) :
mName(name), mValue(value) {}
~Field() {}
const std::string& getName() const {
return mName;
}
T getValue() const {
return mValue;
}
private:
friend class boost::serialization::access;
template<typename Archive>
void serialize(Archive& archive, const unsigned int) {
archive & boost::serialization::make_nvp("Name", mName);
archive & boost::serialization::make_nvp("Value", mValue);
}
std::string mName;
T mValue;
};
BOOST_CLASS_IMPLEMENTATION( Field<int>, boost::serialization::object_serializable )
BOOST_CLASS_IMPLEMENTATION( Field<std::chrono::milliseconds>, boost::serialization::object_serializable )
I'm creating the following object:
Field<std::chrono::milliseconds> mSimTime;
Let's say you have:
auto earlier = std::chrono::system_clock::now();
auto now = std::chrono::system_clock::now();
auto aLotOfMilliseconds= std::chrono::duration_cast<std::chrono::milliseconds>(
now - earlier);
// Serialize here int64_t.
then after deserialization, you have:
std::chrono::duration<int64_t, std::milli> duration(aLotOfMilliseconds);

Convert C++/CLI User Defined Object (%) to Native C++ object (&)

How can I convert a user defined object passed by (%) to a native object (&). For example
void managed_func(user_defined_managed_obj% m_obj_)
{
// i need this
obj_ptr->unmanaged_func(&m_obj_);
}
Thus, in the above example I would like to pass the managed object %m_obj_ to the argument of the unmanaged_func. Here user_defined_managed_obj is a .net wrapper in C++/CLI that is a bridge for a native C++.
I've tried the following:
pin_ptr<user_defined_unmanaged_obj> tmp_ptr = &m_obj_;
obj_ptr->unmanaged_func(*tmp_ptr);
Will someone point me into the right direction or let me know what I can do to remedy this problem. Thank you.
Edit:
The user_defined_unmanaged_obj is a native C++ object and the user_defined_managed_obj is the wrapper C++/CLI class for it.
Edit:
The following are the code
In native C++, native_sql.h
#include <string>
class native_sql
{
public:
native_sql(string arguments)
{...some codes}
~native_sql(void) = default;
void connect(void) {...some codes}
void clean(void) {...some codes}
}
In native C++, native_upload_specific_data.h
#include "native_sql.h"
#include <string>
class native_upload_specific_data
{
public:
native_upload_specific_data(string arugments) {...some codes}
~native_upload_specific_data(void)
void upload(native_sql& sql_obj_) {...some codes}
}
In C++/CLI, sql_wrapper.h
#include <msclr\marshal_cppstd.h>
#include "../native_sql.h"
#include "../native_sql.cpp"
using namespace System;
public ref class sql_wrapper
{
public:
sql_wrapper(String^ arguments)
{...codes to convert String^ to std::string and pass args to
new native_sql}
~sql_wrapper(void) { delete sql_ptr; }
void connect_wrapper(void) { sql_ptr->connect(); }
void clean_wrapper(void) { sql_ptr->clean(); }
native_sql* sql_ptr;
}
In C++/CLI wrapper, upload_specific_data_wrapper.h
#include "../native_upload_specific_data.h"
#include "../native_upload_specific_data.cpp"
using namespace System;
public ref class upload_specific_data_wrapper
{
public:
upload_specific_data_wrapper(String^ arguments)
{...convert String^ args into std::strings and pass to
native_upload_specific_data ctor}
~upload_specific_data_wrapper(void) { delete data_ptr; }
void upload(sql_wrapper% sql_obj_)
{
// here is where I have the problem
pin_ptr<native_sql*> ptr = &(sql_obj_.sql_ptr);
data_ptr->upload(ptr);
}
native_upload_specific_data* data_ptr;
}
The error I receive is
C2664: 'void native_upload_specific_data(native_sql&)': cannot convert arugment 1 from cli::pin_ptr<native_sql*> to native_sql&
....Thank you.

Importing an Embarcadero C++ Builder XE3 DLL into Embarcadero C++ Builder XE3

I try to create a DLL in Embarcadero C++ Builder XE3, and use it in a test-project in the same environment.
I take example on a tutorial which code does not give a good result for me (!) : http://docwiki.embarcadero.com/RADStudio/XE3/en/Tutorial:_Using_Dynamic_Linked_Libraries_in_C%2B%2BBuilder_Applications
Here is the content of my DLL :
BaseAuth.h file :
#ifndef BaseAuthH
#define BaseAuthH
#include <System.hpp>
class TBaseAuth
{
public:
virtual void TestMessage() = 0;
};
#endif // BaseAuthH
Auth.h file :
//---------------------------------------------------------------------------
#ifndef AuthH
#define AuthH
//---------------------------------------------------------------------------
#include "BaseAuth.h"
class TAuth : public TBaseAuth
{
public:
TAuth();
~TAuth();
void TestMessage();
};
#endif
Auth.cpp file :
//---------------------------------------------------------------------------
#pragma hdrstop
#include "Auth.h"
//---------------------------------------------------------------------------
#pragma package(smart_init)
TAuth::TAuth()
{
}
TAuth::~TAuth()
{
}
void TAuth::TestMessage()
{
MessageBox(0, "Test message", "Test", MB_OK);
}
and File1.cpp :
#pragma hdrstop
#pragma argsused
#include "Auth.h"
extern "C" __declspec(dllexport) void* __stdcall GetClassInstance()
{
return static_cast<void*>(new TAuth());
}
extern "C" int _libmain(unsigned long reason)
{
return 1;
}
Now in the test application I have :
the same BaseAuth.h file
a form with a Button :
Test_DLLAuthOrga.h :
#ifndef Test_DLLAuthOrgaH
#define Test_DLLAuthOrgaH
//---------------------------------------------------------------------------
#include <System.Classes.hpp>
#include <Vcl.Controls.hpp>
#include <Vcl.StdCtrls.hpp>
#include <Vcl.Forms.hpp>
//---------------------------------------------------------------------------
#include "BaseAuth.h"
//---------------------------------------------------------------------------
class TForm1 : public TForm
{
__published: // Composants gérés par l'EDI
TButton *Button2;
void __fastcall Button2Click(TObject *Sender);
private: // Déclarations utilisateur
TBaseAuth *mpAuth;
public: // Déclarations utilisateur
__fastcall TForm1(TComponent* Owner);
};
//---------------------------------------------------------------------------
extern PACKAGE TForm1 *Form1;
//---------------------------------------------------------------------------
#endif
Test_DLLAuthOrga.cpp :
//---------------------------------------------------------------------------
#include <vcl.h>
#pragma hdrstop
#include "Test_DLLAuthOrga.h"
#include "BaseAuth.h"
//---------------------------------------------------------------------------
#pragma package(smart_init)
#pragma resource "*.dfm"
TForm1 *Form1;
//---------------------------------------------------------------------------
const wchar_t* library = L"DLLAuthOrga.dll";
extern "C" __declspec(dllimport) void* __stdcall GetClassInstance();
//---------------------------------------------------------------------------
__fastcall TForm1::TForm1(TComponent* Owner) : TForm(Owner)
{
HINSTANCE load;
try
{ load = LoadLibrary(library); }
catch(Exception &e)
{ ShowMessage(e.Message); }
if (load)
{
ShowMessage("Library Loaded!");
void *myFunc;
myFunc = (void *)GetProcAddress(load, "GetClassInstance");
mpAuth = (AuthParent*)myFunc;
}
else { ShowMessage("Library not loaded!"); }
}
//---------------------------------------------------------------------------
void __fastcall TForm1::Button1Click(TObject *Sender)
{
if (mpAuth == NULL) return;
try { pRes = mpAuth->TestMessage(); }
catch(Exception &e) { ShowMessage(e.Message); return; }
}
The result is :
the pointer mpAuth has an adress.
But its methods have no adress, and when I call a simple method such as "void TestMessage()", it raises an access violation.
=> It first seemed to be a question of string compatibility (but between "C++ Builder XE3" and "C++ Builder XE3" I would expect the same string format to be used ?!) : Error calling DLL with Unicode Delphi
=> I found a similar issue but with C++ DLL into Delphi, not C++ DLL into C++ ... : Call C++ DLL in Delphi app
=> I tried using "HMODULE" instead of "HINSTANCE load;" : same result.
=> I tried without success using
mpAuth = static_cast<AuthParent*>(myFunc);
instead of :
mpAuth = (AuthParent*)myFunc;
=> I also tried replacing "__stdcall" by "__cdecl" or "" (removing) : the libray loads but GetProcAdress returns NULL.
=> What am I doing wrong in attempting to call the DLL's method "TestMessage()" ?
To correctly bind function from dll you should give it full definition, including calling convention, arguments, return type and __dllexport/__dllimport modifier. The easiest way to do it - using typedef so instead of typing (in Test_DLLAuthOrga.cpp)
void *myFunc;
myFunc = (void *)GetProcAddress(load, "GetClassInstance");
use
typedef __declspec(dllimport) void (__stdcall *MyFuncPointerType)(void);
MyFuncPointerType myFunc;
myFunc = (MyFuncPointerType)GetProcAddress(load, "GetClassInstance");
If you are using __cdecl convention you should also add underscore to the target function name
typedef __declspec(dllimport) void (__cdecl *MyFuncPointerType)(void);
MyFuncPointerType myFunc;
myFunc = (MyFuncPointerType)GetProcAddress(load, "_GetClassInstance");
you can also explicitly define AuthParent* as a return type for your factory function to get rid of uneccessary casts to void* and back to AuthParent* (in File1.cpp and Test_DLLAuthOrga.cpp) so, the final code snippet would look like this:
typedef __declspec(dllimport) AuthParent* (__cdecl *MyFuncPointerType)(void);
MyFuncPointerType myFunc;
myFunc = (MyFuncPointerType)GetProcAddress(load, "_GetClassInstance");
mpAuth = myFunc();

how to access variable from one class in another in QT mobility?

I have two classes: first generate position data (latitude and longitude), how I can access this data (variables latitude and longitute) in second class? becouse in second class I get crazy number(
Here are headers and classes:
first header:
#ifndef MAINWINDOW_H
#define MAINWINDOW_H
#include <QMainWindow>
#include <QGeoPositionInfoSource>
#include <QGeoPositionInfo>
#include <QtCore/QPointer>
#include <QGeoSatelliteInfo>
#include <QGeoSatelliteInfoSource>
#include "gpsform.h"
QTM_USE_NAMESPACE
namespace Ui {
class MainWindow;
}
class MainWindow : public QMainWindow
{
Q_OBJECT
public:
explicit MainWindow(QWidget *parent = 0);
~MainWindow();
double latitude;
double longitude;
double altitude;
double speed;
public slots:
void positionUpdated(QGeoPositionInfo geoPositionInfo);
private:
Ui::MainWindow *ui;
QPointer<QGeoPositionInfoSource> locationDataSource;
private slots:
void on_pushButton_2_clicked();
void on_pushButton_4_clicked();
void startGPS();
void on_pushButton_clicked();
signals:
void updated();
};
#endif // MAINWINDOW_H
first class
#include "mainwindow.h"
#include "ui_mainwindow.h"
#include "quitdiallog.h"
#include <QGeoCoordinate>
#include <QDebug>
#include <QtGui/QMessageBox>
#include <QList>
#include "gpsform.h"
MainWindow::MainWindow(QWidget *parent) :
QMainWindow(parent),
ui(new Ui::MainWindow)
{
setWindowTitle("Мой кОмпаС");
ui->setupUi(this);
startGPS();
}
MainWindow::~MainWindow()
{
delete ui;
}
void MainWindow::startGPS()
{
// Obtain the location data source if it is not obtained already
if (!locationDataSource)
{
locationDataSource =
QGeoPositionInfoSource::createDefaultSource(this);
if (locationDataSource)
{
// Whenever the location data source signals that the current
// position is updated, the positionUpdated function is called.
QObject::connect(locationDataSource,
SIGNAL(positionUpdated(QGeoPositionInfo)),
this,
SLOT(positionUpdated(QGeoPositionInfo)));
// Start listening for position updates
locationDataSource->setUpdateInterval(100);
locationDataSource->setPreferredPositioningMethods(QGeoPositionInfoSource::SatellitePositioningMethods);
locationDataSource->startUpdates();
} else {
// Not able to obtain the location data source
// TODO: Error handling
}
} else {
// Start listening for position updates
locationDataSource->setUpdateInterval(5000);
locationDataSource->startUpdates();
}
}
void MainWindow::positionUpdated(QGeoPositionInfo geoPositionInfo)
{
//gpsform *gpf=new gpsform;
if (geoPositionInfo.isValid())
{
//locationDataSource->stopUpdates();
QGeoCoordinate geoCoordinate = geoPositionInfo.coordinate();
latitude = geoCoordinate.latitude();
longitude = geoCoordinate.longitude();
altitude=geoCoordinate.altitude();
ui->label->setNum(latitude);
ui->label_2->setNum(longitude);
/*if(QGeoPositionInfo::GroundSpeed)
{
speed=QGeoPositionInfo::GroundSpeed;
ui->label_4->setNum(speed);
}*/
emit updated();
//gpf->latitude=this->latitude;
//gpsform *gpf=new gpsform;
//gpf->show();
//gpf->latitude=latitude;
}
}
void MainWindow::on_pushButton_clicked()
{
/*ui->label_3->setNum(latitude);
qDebug()<<latitude<<" "<<longitude<<" "<<altitude;*/
gpsform *gps=new gpsform;
this->hide();
gps->show();
}
void MainWindow::on_pushButton_4_clicked()
{
QuitDiallog *qi=new QuitDiallog;
this->hide();
qi->show();
}
void MainWindow::on_pushButton_2_clicked()
{
ui->label_3->setNum(latitude);
}
second header
#ifndef GPSFORM_H
#define GPSFORM_H
#include <QWidget>
#include "mainwindow.h"
QTM_USE_NAMESPACE
namespace Ui {
class gpsform;
}
class gpsform : public QWidget
{
Q_OBJECT
public:
explicit gpsform(QWidget *parent = 0);
~gpsform();
double latitude;
private:
Ui::gpsform *ui;
private slots:
void on_pushButton_clicked();
void updatedata();
};
#endif // GPSFORM_H
second class:
#include "gpsform.h"
#include "ui_gpsform.h"
#include "mainwindow.h"
#include <QTimer>
#include <QDebug>
gpsform::gpsform(QWidget *parent) :
QWidget(parent),
ui(new Ui::gpsform)
{
ui->setupUi(this);
/*ui->label->setNum(mw->latitude);*/
/* QTimer * timer = new QTimer(this);
connect(timer,SIGNAL(timeout()),this,SLOT(update()));
timer->start(50);*/
/* MainWindow *mw = new MainWindow;
QObject::connect(mw,SIGNAL(updated()),this,SLOT(updatedata()));*/
}
gpsform::~gpsform()
{
delete ui;
}
void gpsform::updatedata()
{
/* MainWindow *mw = new MainWindow;
this->latitude=mw->latitude;
ui->label->setNum(mw->latitude);*/
}
void gpsform::on_pushButton_clicked()
{
MainWindow *mw = new MainWindow;
//latitude=mw->latitude;
qDebug()<<mw->latitude;
ui->label->setNum(latitude);
}
For example I want to see latitude in second class, by pressing button. In future I'll do this by Signal/slot to generate label text every time, the position is updated. But now I'll get crazy number. Help me please
MainWindow *mw = new MainWindow;
//latitude=mw->latitude;
qDebug()<<mw->latitude;
You create a new instance of MainWindow and directly access its latitude member. But was it initialized? I see the only place writing into this member in MainWindow is positionUpdated. Are you sure this method gets invoked before you access mw->latitude? You could easily verify that with another qDebug printout from positionUpdated, or by using the debugger.
To comment on the code style in general - it's not good practice to directly access members of other classes like this. One of the problems (as you've just encountered!) with this approach is that the class has no way to actually control the validity of its member. Even the most basic solution - having an accessor method instead of raw member access could do wonders for you here, because the accessor method could potentially check if the value has been computed (or even compute it lazily).