Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions concerning problems with code you've written must describe the specific problem — and include valid code to reproduce it — in the question itself. See SSCCE.org for guidance.
Closed 9 years ago.
Improve this question
I post all the files of my project, It seems to be done correct, but this error is incomprensible for me...
mainwindow.h
#ifndef MAINWINDOW_H
#define MAINWINDOW_H
#include <QMainWindow>
#include <activemq/library/ActiveMQCPP.h>
#include <decaf/lang/Thread.h>
#include <decaf/lang/Runnable.h>
#include <decaf/util/concurrent/CountDownLatch.h>
#include <decaf/lang/Integer.h>
#include <decaf/lang/Long.h>
#include <decaf/lang/System.h>
#include <activemq/core/ActiveMQConnectionFactory.h>
#include <activemq/util/Config.h>
#include <cms/Connection.h>
#include <cms/Session.h>
#include <cms/TextMessage.h>
#include <cms/BytesMessage.h>
#include <cms/MapMessage.h>
#include <cms/ExceptionListener.h>
#include <cms/MessageListener.h>
#include "IfacomAmqSender.h"
using namespace activemq::core;
using namespace decaf::util::concurrent;
using namespace decaf::util;
using namespace decaf::lang;
using namespace cms;
namespace Ui {
class MainWindow;
}
class MainWindow : public QMainWindow,public MessageListener
{
Q_OBJECT
public:
explicit MainWindow(QWidget *parent = 0);
~MainWindow();
void onMessage(const Message*);
void connetionSender();
IfacomAmqSender m_IfacomMessageBroker;
private slots:
void on_pushButton_clicked();
private:
Ui::MainWindow *ui;
};
#endif // MAINWINDOW_H
mainwindow.cpp
#include "mainwindow.h"
#include "ui_mainwindow.h"
#include "IfacomAmqSender.h"
#include "IfacomAmqReceiver.h"
#include <activemq/library/ActiveMQCPP.h>
#include <decaf/lang/Thread.h>
#include <decaf/lang/Runnable.h>
#include <decaf/util/concurrent/CountDownLatch.h>
#include <decaf/lang/Integer.h>
#include <decaf/lang/Long.h>
#include <decaf/lang/System.h>
#include <activemq/core/ActiveMQConnectionFactory.h>
#include <activemq/util/Config.h>
#include <cms/Connection.h>
#include <cms/Session.h>
#include <cms/TextMessage.h>
#include <cms/BytesMessage.h>
#include <cms/MapMessage.h>
#include <cms/ExceptionListener.h>
#include <cms/MessageListener.h>
#include <stdlib.h>
#include <stdio.h>
#include <iostream>
#include <memory>
#include <qstring.h>
#include <QTextStream>
#include <QMessageBox>
using namespace activemq::core;
using namespace decaf::util::concurrent;
using namespace decaf::util;
using namespace decaf::lang;
using namespace cms;
using namespace std;
MainWindow::MainWindow(QWidget *parent) :
QMainWindow(parent),
ui(new Ui::MainWindow)
{
ui->setupUi(this);
}
MainWindow::~MainWindow()
{
delete ui;
}
void MainWindow::connetionSender()
{
activemq::library::ActiveMQCPP::initializeLibrary();
std::string brokerURI = "failover://(tcp://localhost:61613?wireFormat=stomp)"; // localhost;
// brokerURI = "failover://(tcp://localhost:61616)"; // localhost
// Queue name
std::string destName = "IFACOM-CMS";
// Queue or Topic
bool useTopics = false; // true=Topic, false=Queue
// SESSION_TRANSACTED or AUTO_ACKNOWLEDGE
bool sessionTransacted = false; // if true, commit all messages
// ***** Initialisation **************************************************************
IfacomAmqSender m_IfacomMessageBroker(brokerURI, useTopics, sessionTransacted, destName);
m_IfacomMessageBroker.initConnection();
IfacomAmqReceiver IfacomAmqReceiverBroker(brokerURI,10, useTopics, sessionTransacted, destName,2000);
IfacomAmqReceiverBroker.initConnection();
IfacomAmqReceiverBroker.getConsumer()->setMessageListener(this);
}
void MainWindow::on_pushButton_clicked()
{
//****** Send message ******************************************************
//IfacomAmqSender IfacomAmqReceiverBroker;
std::string text = "My IFaCOM message";
// Customized message
try{
std::auto_ptr<TextMessage> message(m_IfacomMessageBroker.getSession()->createTextMessage(text));
message->setCMSTimestamp(System::currentTimeMillis());
message->setStringProperty("MyProperty", "test");
m_IfacomMessageBroker.sendMessage(message);
} catch (CMSException& e) {
e.printStackTrace();
}
// Simple text message
m_IfacomMessageBroker.sendMessage(text);
long long startTime = System::currentTimeMillis();
long long endTime = System::currentTimeMillis();
double totalTime = (double)(endTime - startTime) / 1000.0;
// Close the connection
m_IfacomMessageBroker.close();
//ui->label->setText(QString::fromStdString(text));
// To Do at the end
//activemq::library::ActiveMQCPP::shutdownLibrary();
}
//***************** Receive Message *****************************************************
void MainWindow::onMessage(const Message* message) {
try {
const TextMessage* textMessage = dynamic_cast<const TextMessage*> (message);
string text = "";
if (textMessage != NULL) {
text = textMessage->getText();
} else {
text = "NOT A TEXTMESSAGE!";
}
//printf("Message received: %s\n", text.c_str());
//WM get param.
std::string msgId = message->getCMSMessageID();
int prio = message->getCMSPriority();
long long timestamp = message->getCMSTimestamp();
ui->label->setText(QString::fromStdString(text));
} catch (CMSException& e) {
e.printStackTrace();
}
// Commit all messages.
/*if (this->m_sessionTransacted) {
m_session->commit();
}
// No matter what, tag the count down latch until done.
m_doneLatch.countDown();*/
}
IfacomAmqReceiver.h
#ifndef _IfacomAmqReceiver_h
#define _IfacomAmqReceiver_h
#include <activemq/library/ActiveMQCPP.h>
#include <decaf/lang/Thread.h>
#include <decaf/lang/Runnable.h>
#include <decaf/util/concurrent/CountDownLatch.h>
#include <decaf/lang/Integer.h>
#include <decaf/lang/Long.h>
#include <decaf/lang/System.h>
#include <activemq/core/ActiveMQConnectionFactory.h>
#include <activemq/util/Config.h>
#include <cms/Connection.h>
#include <cms/Session.h>
#include <cms/TextMessage.h>
#include <cms/BytesMessage.h>
#include <cms/MapMessage.h>
#include <cms/ExceptionListener.h>
#include <cms/MessageListener.h>
#include <stdlib.h>
#include <stdio.h>
#include <iostream>
#include <memory>
using namespace activemq::core;
using namespace decaf::util::concurrent;
using namespace decaf::util;
using namespace decaf::lang;
using namespace cms;
class IfacomAmqReceiver : public ExceptionListener, public MessageListener{
private:
CountDownLatch m_latch;
CountDownLatch m_doneLatch;
Connection* m_connection;
Session* m_session;
Destination* m_destination;
MessageConsumer* m_consumer;
MessageProducer* m_producer;
std::auto_ptr<TextMessage> m_message;
long m_waitMillis;
bool m_useTopic;
bool m_sessionTransacted;
std::string m_brokerURI;
std::string m_destName;
DeliveryMode m_message_delivery_mode;
int m_message_priority;
//IfacomAmqReceiver(const IfacomAmqReceiver&);
//IfacomAmqReceiver& operator=(const IfacomAmqReceiver&);
public:
IfacomAmqReceiver(const std::string&, int, bool, bool, const std::string&, int);
virtual ~IfacomAmqReceiver();
void close();
void waitUntilReady() ;
void cleanup();
// MM
void createConnection();
void createSession();
void createDestination();
void createConsumer();
void initConnection();
void onMessage(const Message*);
MessageConsumer* getConsumer();
// If something bad happens you see it here as this class is also been
// registered as an ExceptionListener with the connection.
void onException(const CMSException&);
};
#endif
IfacomAmqReceiver.cpp
#include <activemq/library/ActiveMQCPP.h>
#include <decaf/lang/Thread.h>
#include <decaf/lang/Runnable.h>
#include <decaf/util/concurrent/CountDownLatch.h>
#include <decaf/lang/Integer.h>
#include <decaf/lang/Long.h>
#include <decaf/lang/System.h>
#include <activemq/core/ActiveMQConnectionFactory.h>
#include <activemq/util/Config.h>
#include <cms/Connection.h>
#include <cms/Session.h>
#include <cms/TextMessage.h>
#include <cms/BytesMessage.h>
#include <cms/MapMessage.h>
#include <cms/ExceptionListener.h>
#include <cms/MessageListener.h>
#include <stdlib.h>
#include <stdio.h>
#include <iostream>
#include <memory>
#include "IfacomAmqReceiver.h"
using namespace activemq::core;
using namespace decaf::util::concurrent;
using namespace decaf::util;
using namespace decaf::lang;
using namespace cms;
using namespace std;
IfacomAmqReceiver::IfacomAmqReceiver(const std::string& brokerURI, int numMessages, bool useTopic = false, bool sessionTransacted = false, const std::string& destName = "IFACOM-CMS", int waitMillis = 1000) :
m_latch(1),
m_doneLatch(numMessages),
m_connection(NULL),
m_session(NULL),
m_destination(NULL),
m_consumer(NULL),
m_waitMillis(waitMillis),
m_useTopic(useTopic),
m_sessionTransacted(sessionTransacted),
m_destName(destName),
m_brokerURI(brokerURI) {
}
IfacomAmqReceiver::~IfacomAmqReceiver() {
cleanup();
}
void IfacomAmqReceiver::close() {
this->cleanup();
}
void IfacomAmqReceiver::waitUntilReady() {
m_latch.await();
}
//------ Init connexion ---------------
void IfacomAmqReceiver::createConnection()
{
// Create a ConnectionFactory
auto_ptr<ConnectionFactory> connectionFactory(ConnectionFactory::createCMSConnectionFactory(m_brokerURI));
// Create a Connection
m_connection = connectionFactory->createConnection();
m_connection->start();
m_connection->setExceptionListener(this);
}
void IfacomAmqReceiver::createSession()
{
// Create a Session
if (this->m_sessionTransacted == true) {
m_session = m_connection->createSession(Session::SESSION_TRANSACTED);
} else {
m_session = m_connection->createSession(Session::AUTO_ACKNOWLEDGE);
}
}
void IfacomAmqReceiver::createDestination()
{
// Create the destination (Topic or Queue)
if (m_useTopic) {
m_destination = m_session->createTopic(m_destName);
} else {
m_destination = m_session->createQueue(m_destName);
}
}
void IfacomAmqReceiver::createConsumer()
{
m_consumer = m_session->createConsumer(m_destination);
//m_consumer->setMessageListener(this);
}
void IfacomAmqReceiver::initConnection() {
try {
createConnection();
// Create the session
createSession();
// Create the destination (Topic or Queue)
createDestination();
// Create a MessageConsumer from the Session to the Topic or Queue
createConsumer();
// Indicate we are ready for messages.
m_latch.countDown();
// Wait while asynchronous messages come in.
m_doneLatch.await(m_waitMillis);
} catch (CMSException& e) {
// Indicate we are ready for messages.
//latch.countDown();
e.printStackTrace();
}
}
//------ Get the message ---------------
// Called from the consumer since this class is a registered MessageListener.
void IfacomAmqReceiver::onMessage(const Message* message) {}
//--------------------------------------------------
// If something bad happens you see it here as this class is also been
// registered as an ExceptionListener with the connection.
void IfacomAmqReceiver::onException(const CMSException& ex AMQCPP_UNUSED) {
printf("CMS Exception occurred. Shutting down client.\n");
ex.printStackTrace();
exit(1);
}
void IfacomAmqReceiver::cleanup() {
if (m_connection != NULL) {
try {
m_connection->close();
} catch (cms::CMSException& ex) {
ex.printStackTrace();
}
}
// Destroy resources.
try {
delete m_destination;
m_destination = NULL;
delete m_consumer;
m_consumer = NULL;
delete m_session;
m_session = NULL;
delete m_connection;
m_connection = NULL;
} catch (CMSException& e) {
e.printStackTrace();
}
}
MessageConsumer* IfacomAmqReceiver::getConsumer()
{
return m_consumer;
}
IfacomAmqSender.h
#ifndef _IfacomAmqSender_h
#define _IfacomAmqSender_h
#include <activemq/library/ActiveMQCPP.h>
#include <decaf/lang/Thread.h>
#include <decaf/lang/Runnable.h>
#include <decaf/util/concurrent/CountDownLatch.h>
#include <decaf/lang/Integer.h>
#include <decaf/lang/Long.h>
#include <decaf/lang/System.h>
#include <activemq/core/ActiveMQConnectionFactory.h>
#include <activemq/util/Config.h>
#include <cms/Connection.h>
#include <cms/Session.h>
#include <cms/TextMessage.h>
#include <cms/BytesMessage.h>
#include <cms/MapMessage.h>
#include <cms/ExceptionListener.h>
#include <cms/MessageListener.h>
#include <stdlib.h>
#include <stdio.h>
#include <iostream>
#include <memory>
using namespace activemq::core;
using namespace decaf::util::concurrent;
using namespace decaf::util;
using namespace decaf::lang;
using namespace cms;
class IfacomAmqSender : public ExceptionListener{
private:
CountDownLatch m_latch;
CountDownLatch m_doneLatch;
Connection* m_connection;
Session* m_session;
Destination* m_destination;
MessageConsumer* m_consumer;
MessageProducer* m_producer;
std::auto_ptr<TextMessage> m_message;
long m_waitMillis;
bool m_useTopic;
bool m_sessionTransacted;
std::string m_brokerURI;
std::string m_destName;
DeliveryMode m_message_delivery_mode;
int m_message_priority;
IfacomAmqSender(const IfacomAmqSender&);
IfacomAmqSender& operator=(const IfacomAmqSender&);
public:
IfacomAmqSender(const std::string&, int, bool, bool, const std::string&, int);
IfacomAmqSender(const std::string&, bool, bool, const std::string&);
virtual ~IfacomAmqSender();
void close();
void waitUntilReady();
void cleanup();
// KH
void createConnection();
void createSession();
void createDestination();
void createProducer();
void initConnection();
virtual void sendMessage(std::string);
// Send a ActiveMQ Message
virtual void sendMessage(std::auto_ptr<TextMessage>);
//--------------------------------------------------
// If something bad happens you see it here as this class is also been
// registered as an ExceptionListener with the connection.
virtual void onException(const CMSException&) ;
// Message Priority (0:Lowest - 9:Highest)
void setPriority(int);
int getPriority();
// Message Delivery Mode
void setDeliveryMode(DeliveryMode);
DeliveryMode getDeliveryMode();
Session* getSession();
};
#endif
IfacomAmqSender.cpp
#include <activemq/library/ActiveMQCPP.h>
#include <decaf/lang/Thread.h>
#include <decaf/lang/Runnable.h>
#include <decaf/util/concurrent/CountDownLatch.h>
#include <decaf/lang/Integer.h>
#include <decaf/lang/Long.h>
#include <decaf/lang/System.h>
#include <activemq/core/ActiveMQConnectionFactory.h>
#include <activemq/util/Config.h>
#include <cms/Connection.h>
#include <cms/Session.h>
#include <cms/TextMessage.h>
#include <cms/BytesMessage.h>
#include <cms/MapMessage.h>
#include <cms/ExceptionListener.h>
#include <cms/MessageListener.h>
#include <stdlib.h>
#include <stdio.h>
#include <iostream>
#include <memory>
#include "IfacomAmqSender.h"
using namespace activemq::core;
using namespace decaf::util::concurrent;
using namespace decaf::util;
using namespace decaf::lang;
using namespace cms;
using namespace std;
IfacomAmqSender::IfacomAmqSender(const std::string& brokerURI, int numMessages, bool useTopic = false, bool sessionTransacted = false, const std::string& destName = "IFACOM-CMS", int waitMillis = 1000) :
m_latch(1),
m_doneLatch(numMessages),
m_connection(NULL),
m_session(NULL),
m_destination(NULL),
m_consumer(NULL),
m_waitMillis(waitMillis),
m_useTopic(useTopic),
m_sessionTransacted(sessionTransacted),
m_destName(destName),
m_brokerURI(brokerURI) {
}
IfacomAmqSender::IfacomAmqSender(const std::string& brokerURI, bool useTopic = false, bool sessionTransacted = false, const std::string& destName = "IFACOM-CMS") :
m_latch(1),
m_doneLatch(1),
m_connection(NULL),
m_session(NULL),
m_destination(NULL),
m_consumer(NULL),
m_waitMillis(1000),
m_useTopic(useTopic),
m_sessionTransacted(sessionTransacted),
m_destName(destName),
m_brokerURI(brokerURI) {
}
IfacomAmqSender::~IfacomAmqSender() {
cleanup();
}
void IfacomAmqSender::close() {
this->cleanup();
}
void IfacomAmqSender::waitUntilReady() {
m_latch.await();
}
//------ Init connexion ---------------
void IfacomAmqSender::createConnection()
{
// Create a ConnectionFactory
auto_ptr<ConnectionFactory> connectionFactory(ConnectionFactory::createCMSConnectionFactory(m_brokerURI));
// Create a Connection
m_connection = connectionFactory->createConnection();
m_connection->start();
m_connection->setExceptionListener(this);
}
void IfacomAmqSender::createSession()
{
// Create a Session
if (this->m_sessionTransacted == true) {
m_session = m_connection->createSession(Session::SESSION_TRANSACTED);
} else {
m_session = m_connection->createSession(Session::AUTO_ACKNOWLEDGE);
}
}
void IfacomAmqSender::createDestination()
{
// Create the destination (Topic or Queue)
if (m_useTopic) {
m_destination = m_session->createTopic(m_destName);
} else {
m_destination = m_session->createQueue(m_destName);
}
}
void IfacomAmqSender::createProducer()
{
m_producer = m_session->createProducer(m_destination);
m_producer->setDeliveryMode(DeliveryMode::NON_PERSISTENT);
}
void IfacomAmqSender::initConnection() {
try {
createConnection();
// Create the session
createSession();
// Create the destination (Topic or Queue)
createDestination();
// Create a MessageProducer from the Session to the Topic or Queue
createProducer();
m_producer->setDeliveryMode(DeliveryMode::NON_PERSISTENT);
// Indicate we are ready for messages.
m_latch.countDown();
// Wait while asynchronous messages come in.
m_doneLatch.await(m_waitMillis);
} catch (CMSException& e) {
// Indicate we are ready for messages.
//latch.countDown();
e.printStackTrace();
}
}
void IfacomAmqSender::sendMessage(string text) {
try {
std::auto_ptr<TextMessage> message(m_session->createTextMessage(text));
// to set a property
////message->setIntProperty("Integer", ix);
m_producer->send(message.get());
message->setCMSTimestamp(System::currentTimeMillis());
} catch (CMSException& e) {
e.printStackTrace();
}
}
// Send a ActiveMQ Message
void IfacomAmqSender::sendMessage(std::auto_ptr<TextMessage> amq_message) {
try {
amq_message->setCMSTimestamp(System::currentTimeMillis());
m_producer->send(amq_message.get());
} catch (CMSException& e) {
e.printStackTrace();
}
}
//--------------------------------------------------
// If something bad happens you see it here as this class is also been
// registered as an ExceptionListener with the connection.
void IfacomAmqSender::onException(const CMSException& ex AMQCPP_UNUSED) {
printf("CMS Exception occurred. Shutting down client.\n");
ex.printStackTrace();
exit(1);
}
// Message Priority (0:Lowest - 9:Highest)
void IfacomAmqSender::setPriority(int priority){m_message_priority = priority;}
int IfacomAmqSender::getPriority(){return m_message_priority;}
// Message Delivery Mode
void IfacomAmqSender::setDeliveryMode(DeliveryMode delivery_mode){m_message_delivery_mode = delivery_mode;}
DeliveryMode IfacomAmqSender::getDeliveryMode(){return m_message_delivery_mode;}
Session* IfacomAmqSender::getSession()
{
return m_session;
}
void IfacomAmqSender::cleanup() {
if (m_connection != NULL) {
try {
m_connection->close();
} catch (cms::CMSException& ex) {
ex.printStackTrace();
}
}
// Destroy resources.
try {
delete m_destination;
m_destination = NULL;
delete m_consumer;
m_consumer = NULL;
delete m_session;
m_session = NULL;
delete m_connection;
m_connection = NULL;
} catch (CMSException& e) {
e.printStackTrace();
}
}
main.cpp
#include "ifacomamqsender.h"
#include "mainwindow.h"
#include <QApplication>
int main(int argc, char *argv[])
{
QApplication a(argc, argv);
MainWindow w;
w.show();
return a.exec();
}
and the error is:
Error 29 error C2512: 'IfacomAmqSender' : no appropriate default constructor available 42 1 GUI-CMS
In MainWindow you have a member variable called m_IfacomMessageBroker which is a IfacomAmqSender. This class doesn't have a default constructor, so you must call one of its constructors in the initialization list for MainWindow.
You're not doing this, so the compiler assumes you want to call the default construtor, and it notices that there isn't one, so you get the error. The reason there isn't a default constructor if because you've created your own constructors, so the compiler generated default doesn't exist. Therefore if you want a default constructor you need to manually create it.
I don't see a default constructor in the definition of the IfacomAmqSender object, but you have an instance of it in your MainWindow.
You have this line.
IfacomAmqSender m_IfacomMessageBroker;
This is trying to call a no arg constructor, and you don't have one.
You have:
IfacomAmqSender(const std::string&, int, bool, bool, const std::string&, int);
IfacomAmqSender(const std::string&, bool, bool, const std::string&);
... and need:
IfacomAmqSender();
... or you need to assign default values.
If I know right and I do, the default constructor is not available if the programmer is defining a constructor. You have done it, so there is no default constructor, only the ones that you have declared.
No default constructor is available for the specified class, structure, or union. The compiler supplies a default constructor if user-defined constructors are not provided.
If you provide a constructor that takes a non-void parameter, and you want to allow your class to be created with no parameters, you must also provide a default constructor. The default constructor can be a constructor with default values for all parameters.
For More Information refer :
http://msdn.microsoft.com/en-us/library/9zkz8dx6.aspx
Related
I wrote a simple threadpool server with qt. When i try to connect to server on win 32/64 all works good. But when I use linux centos 7 server is not responding. I use 127.0.0.1:8080 for server address. Also server uses database mysql. When I try to connect via telnet it connects but nothing happens. I checked for open ports with netstat. Maybe I missed something because of this the server is not working?
Here is my code for server. In fact, there is also an http request handler, but it does not reach it, I tried to output a string in the constructor - it is not called.
QthreadPoolServer.cpp
#include "QThreadPoolServer.h"
#include "QSocketRunnable.h"
#include "ConfigReader.h"
#include <memory>
QThreadPoolServer::QThreadPoolServer()
{
ConfigReader reader(config_file_path);
QHostAddress server_IP(reader.getServerAddress());
int port = reader.getServerPort();
listen(QHostAddress::localhost, 8080);
std:: cout << serverError() << errorString().toStdString();
m_threadPool = std::make_shared<QThreadPool>(this);
}
void QThreadPoolServer::incomingConnection(int handle)
{
std::shared_ptr<QSocketRunnable> runnable = std::make_shared<QSocketRunnable>(handle);
runnable->setAutoDelete(false);
m_threadPool->start(runnable.get());
}
QThreadPoolServer::~QThreadPoolServer()
{
m_threadPool->~QThreadPool();
}
QThreadPoolServer.h
#ifndef QTHREADPOOLSERVER_H
#define QTHREADPOOLSERVER_H
#include <QTcpServer>
#include <QThreadPool>
#include <memory>
class QThreadPoolServer : public QTcpServer
{
public:
explicit QThreadPoolServer();
void incomingConnection(int handle);
~QThreadPoolServer();
private:
std::shared_ptr<QThreadPool> m_threadPool;
};
#endif // QTHREADPOOLSERVER_H
QSocketRunnable.cpp
#include "QSocketRunnable.h"
#include <QString>
#include <memory>
#include <iostream>
QSocketRunnable::QSocketRunnable(int handle) : m_descriptor(handle) { }
void QSocketRunnable::run()
{
QTcpSocket* socket = new QTcpSocket();
socket->setSocketDescriptor(m_descriptor);
socket->waitForReadyRead();
QString request_data = QString(socket->readAll());
HttpRequestHandler handler(request_data);
handler.makeResponse();
QString http_response_result = handler.getHttpResponse();
std::cout << http_response_result.toStdString() << "\n";
socket->write(http_response_result.toUtf8());
socket->waitForBytesWritten(90000);
socket->disconnectFromHost();
socket->close();
socket->deleteLater();
}
QSocketRunnable.h
#ifndef QSOCKETRUNNABLE_H
#define QSOCKETRUNNABLE_H
#include <QRunnable>
#include <QTcpSocket>
#include <QtDebug>
#include <QString>
//#include "IDHelper.h"
//#include "JsonFormatter.h"
//#include "HttpRequestHandler.h"
class QSocketRunnable : public QRunnable
{
public:
QSocketRunnable(int handle);
void run() override;
private:
int m_descriptor;
};
#endif // QSOCKETRUNNABLE_H
main.cpp
#include <QCoreApplication>
#include "QThreadPoolServer.h"
#include "signal.h"
#include <sstream>
int main(int argc, char *argv[])
{
QCoreApplication a(argc, argv);
QThreadPoolServer server;
return a.exec();
}
Also std:: cout << serverError() << errorString().toStdString(); returns "-1" that means QAbstractSocket::UnknownSocketError -1 An unidentified error occurred.
As #chehrlic correctly noted: I had an incorrectly overloaded function, so here is the ritht version of QThreadPoolServer.h
QThreadPoolServer.h
#ifndef QTHREADPOOLSERVER_H
#define QTHREADPOOLSERVER_H
#include <QTcpServer>
#include <QThreadPool>
#include <memory>
class QThreadPoolServer : public QTcpServer
{
public:
explicit QThreadPoolServer();
protected:
void incomingConnection(qintptr handle) override;
~QThreadPoolServer();
private:
std::shared_ptr<QThreadPool> m_threadPool;
};
#endif // QTHREADPOOLSERVER_H
My my implementation did not work correctly with a smart pointer to a runnable object:
QThreadPoolServer.cpp
void QThreadPoolServer::incomingConnection(qintptr handle)
{
QSocketRunnable* runnable = new QSocketRunnable(handle)
runnable->setAutoDelete(true);
m_threadPool->start(runnable);
}
I have a dll with lib.h:
#pragma once
#ifdef EXPORTS
#define API __declspec(dllexport)
#else
#define API __declspec(dllimport)
#endif
extern "C" API void test1(std::vector<ValueType*>* functions);
and lib.cpp:
#include "pch.h"
#include <iostream>
#include <vector>
#include "ValueType.h"
#include "NumberValue.h"
#include "TestLib.h"
void test1(std::vector<ValueType*>* functions) {
functions->push_back(new NumberValue(123321));
And main file, that uses this dll is:
#include <iostream>
#include <vector>
#include <Windows.h>
#include "ValueType.h"
using namespace std;
typedef void (__cdecl* importedInitFunction)(std::vector<ValueType*>*);
importedInitFunction test1F;
std::vector<ValueType*> values;
int main() {
while (1) {
HMODULE lib = LoadLibrary("DllTest1.dll");
test1F = (importedInitFunction)GetProcAddress(lib, "test1");
test1F(&values);
FreeLibrary(lib);
std::cout << values.at(0)->asString();
system("pause");
}
return 0;
}
When I'm trying to compile my code, I catch an error because values.at(0) is removed.
How to prevent deleting my variable when calling FreeLibrary(lib) ? or
How to implement alternative way ?
Another classes that used:
ValueType.h:
#pragma once
#include <string>
class ValueType {
public:
virtual double asDouble() { return 999; }
virtual std::string asString() { return ""; }
};
NumberValue.h:
#pragma once
#include <string>
#include "ValueType.h"
class NumberValue : public ValueType {
public:
double m_value;
NumberValue(double value) : m_value(value) {}
virtual double asDouble() {
return m_value;
}
virtual std::string asString() {
return std::to_string(m_value);
}
};
I have a class Project and each Project can have different tasks.
Project.h:
#pragma once
#include "Task.h"
#include <vector>
using namespace std;
class Project
{
private:
vector<Task> Tasks;
public:
Project::Project(int inleesgetal);//constructor
vector<Task> GetTasks();
};
Project.cpp:
#include "Project.h"
#include <string>
#include <vector>
Project::Project(int inleesgetal)
{
//constructor
Tasks.resize(Numbertasks);
}
vector<Task> Project::GetTasks()
{
return Tasks;
}
Task.h:
#pragma once
#include <vector>
using namespace std;
class Task
{
private:
//Info:
int StartTime_Solo;
public:
Task(); //constructor
void SetStartTime_Solo(int st_s);
int GetStartTime_Solo();
};
Task.cpp:
#include "Task.h"
#include <string>
#include <vector>
#include <iostream>
using namespace std;
Task::Task()
{
//constructor
StartTime_Solo = 0;
}
int Task::GetStartTime_Solo()
{
return StartTime_Solo;
}
void Task::SetStartTime_Solo(int st_s)
{
StartTime_Solo = st_s;
}
main:
#include <iostream>
#include <vector>
#include "Task.h"
#include "Project.h"
using namespace std;
int main()
{
Project Project1(6);
Project1.GetTasks()[2].SetStartTime_Solo(55);
cout << "test:" << Project1.GetTasks()[2].GetStartTime_Solo();
return 0;
}
Now when I try to set the 3rd task of Project1 to a starttime of 55 and then print the start time out it still gives me 0 as a result.
Why is this? And how can I change my code so it actually sets the starttime to 55?
vector<Task> GetTasks();
should be
const vector<Task>& GetTasks() const;
vector<Task>& GetTasks();
And so with definitions:
vector<Task> Project::GetTasks()
{
return Tasks;
}
should be:
const vector<Task>& Project::GetTasks() const { return Tasks; }
vector<Task>& Project::GetTasks() { return Tasks; }
The problem is that you are returning a copy of the vector<Task> from the GetTasks function. You then modify this copy and throw it away right afterwards. The internal member of Project is not changed.
If you return by reference like this:
vector<Task>& GetTasks();
Then you are basically returning something that points to the internal vector, and so when you modify it, you actually modify the member data of your class.
I'm doing my first project with c++ following the MVC pattern. I have a controller class, Session, which has all functions to manage the class "ClientTsFrm", a view. What I want to do it's to communicate to the view class all events that happen. To do that, I'm using the observer pattern, in fact this implementation 1
Session.h Session is also a singleton.
#pragma once
#include "User.h"
#include "Config.h"
#include "../data/message.h"
#include <list>
#include <cstring>
#include <stdio.h>
#include <cstdlib>
#include "../lib/eventtype.h"
#include "../lib/Subject.h"
#ifndef WX_PRECOMP
#include <wx/wx.h>
#include <wx/frame.h>
#else
#include <wx/wxprec.h>
#endif
#include <wx/richtext/richtextctrl.h>
#include <wx/grid.h>
typedef std::list<UserPTR> UserList;
typedef std::shared_ptr<UserList> UserListPTR;
/*
* Set and get functions
*/
class Session: public Subject<EventTS>{
public:
static Session* Instance();
private:
Session(); // Private so that it can not be called
Session(Session const&){}; // copy constructor is private
Session& operator=(Session const&){}; // assignment operator is private
static Session* m_pInstance;
public:
private:
Session* m_instance;
ConfigPTR m_config;
UserListPTR m_luser;
char* m_translationEngine;
MessageQueuePTR m_pending;
MessageQueuePTR m_queue;
};
Subject.h
//
// Copyright (c) 2013 Juan Palacios juan.palacios.puyana#gmail.com
// Subject to the BSD 2-Clause License
// - see < http://opensource.org/licenses/BSD-2-Clause>
//
#ifndef SUBJECT_H_
#define SUBJECT_H_
#include <functional>
#include <map>
#include <vector>
#include <utility> // for std::forward
template <typename Event>
class Subject
{
public:
Subject()=default;
template <typename Observer>
void registerObserver(const Event& event, Observer&& observer)
{
observers_[event].push_back(std::forward<Observer>(observer));
}
template <typename Observer>
void registerObserver(Event&& event, Observer&& observer)
{
observers_[std::move(event)].push_back(std::forward<Observer>(observer));
}
void notify(const Event& event) const
{
for (const auto& obs : observers_.at(event)) obs();
}
// disallow copying and assigning
Subject(const Subject&)=delete;
Subject& operator=(const Subject&)=delete;
private:
std::map<Event, std::vector<std::function<void()>>> observers_;
};
#endif // SUBJECT_H_
ClientTsFrm.h
#pragma once
#ifdef __BORLANDC__
#pragma hdrstop
#endif
#ifndef WX_PRECOMP
#include <wx/wx.h>
#include <wx/frame.h>
#else
#include <wx/wxprec.h>
#endif
#include "../Data/config.h"
#include "../lib/ClientTS.h"
#include "../data/Session.h"
#include "../data/Message.h"
#include "FrmMailSending.h"
#include "FrmSettingMail.h"
#include "AudioWizard.h"
#include "NationList.h"
#include "LoginWarnings.h"
#include "../ArchiveLog.h"
#include "FrmSaveChat.h"
#include <wx/sizer.h>
#include <wx/wx.h>
#include <wx/timer.h>
#include <wx/stattext.h>
#include <wx/richtext/richtextctrl.h>
#include <wx/textctrl.h>
#include <wx/button.h>
#include <wx/grid.h>
#include "../GlobalVariables.h"
#include "../translateController/translateController.h"
#include "../translateController/translateVariable.h"
#include <list>
//#include "../lib/Observer.h"
#define MENU_ESCI 1800
#define MENU_OPZIONI 1801
#define MENU_SPEECH 1802
class ClientTsFrm : public wxFrame
{
ClientTsFrm(LoginWarnings *warn, wxWindow *parent, wxWindowID id = 1, const wxString &title = wxT("TeamTranslate"),
const wxPoint& pos = wxDefaultPosition, const wxSize& size = wxDefaultSize,
long style = wxCAPTION | wxSYSTEM_MENU | wxCLOSE_BOX | wxRESIZE_BORDER);
virtual ~ClientTsFrm(){};
ClientTsFrm(const ClientTsFrm& tg) {
std::cout << "\tSimpleCat(SimpleCat&) called\n";
}
void updatePanelMsg();
private:
unsigned int curRow; //Initialize Row index
unsigned int curCol; //Initialize Column index
Session* session;
ConfigPTR config;
NationList *nations;
int REFRESHTIMER = 0;
uint64 _sclogID;
wxTimer *WxTimer2;
wxTimer *WxTimer1;
wxButton *btnspeech;
wxRichTextCtrl *txtclient;
wxTextCtrl *txtlingua;
wxStaticText *lbllingua;
wxStaticText *lblnick;
wxTextCtrl *txtnick;
wxRichTextCtrl *txtchat;
wxButton *btnsend;
wxTextCtrl *txtmsg;
wxGrid *gridchat;
wxGrid *gridclient;
wxBoxSizer *sizer;
wxGridSizer *gridsizer;
wxMenuBar *WxMenuBar1;
wxMenu *ID_MNU_FILE_1001_Mnu_Obj;
wxMenu *ID_MNU_OPZIONI_1004_Mnu_Obj;
wxBitmapButton *WxBitmapButton1;
ClientTS clientts;
};
ClientTS.cpp. This is how I register the object
...
session->registerObserver(EventTS::MSG_RCV, std::bind(notifyMSG, *this));
...
void notifyMSG(ClientTsFrm *fn)
{
fn->updatePanelMsg();
}
Basically, I'm registering ClientTSFrm object. It's stored in session class and when an event happens, session calls the "notify" function from the subject class. This function calls the function of ClientTSFrm (the observer) which is send also the object. At the end, this function calls a function of ClientTSFrm class in order to update the content.
If I compile, it shows this error:
Error 28 error C2664: 'void (ClientTsFrm *)' : cannot convert argument
1 from 'ClientTsFrm' to 'ClientTsFrm *' C:\Program Files
(x86)\Microsoft Visual Studio 12.0\VC\include\functional 1149 1
https://github.com/juanchopanza/cppblog/blob/master/Patterns/Observer/
Im new in C++, and i got a program called sendSMS:
#include "ServerSocket.h"
#include "SocketException.h"
#include <string>
#include <vector>
#include <iostream>
#include <fstream>
#include "Socket.h"
#include <pthread.h>
#include <stdio.h>
#include "Config.h"
#include <mysql/mysql.h>
#include <cstdlib>
#include <SerialStream.h>
void *func_servidor(void *ptr_timer);
ServerSocket server(30001);
pthread_t thread_servidor;
pthread_t thread_transfdados;
pthread_t thread_BD;
pthread_cond_t cv;
pthread_mutex_t mp;
int ret;
#define CTRL_C "\x1A"
const int PORT_MON = 30000;
const string serialPort = "/dev/ttyS0";
using namespace LibSerial;
using namespace std;
int setSerial(SerialStream& ssStream, const string& port) {
...
....
}
int sendsms(int argc, char **argv) {
bool send = true;
...
....
return(0);
}
void *func_servidor(void *ptr)
{
...
....
return(0);
}
I want to transfer all those functions to a header .h file and call it in a main program(main.cpp), so the main.cpp only calls "everything" like:
#include sendSMS.h
class modem{
{
public:
void SendSms();
}
int main{
SendSms();
return(0);
}
And the header will be like?
#ifndef __SENDSMS__
#define __SENDSMS__
#include "ServerSocket.h"
#include "SocketException.h"
#include <string>
#include <vector>
#include <iostream>
#include <fstream>
#include "Socket.h"
#include <pthread.h>
#include <stdio.h>
#include "Config.h"
#include <mysql/mysql.h>
#include <cstdlib>
#include <SerialStream.h>
class sendsms
{
private:
int ret;
const int PORT_MON;
int argc;
const string serialPort;
char **argv;
bool send;
public:
sendsms();
void *func_servidor(void *ptr);
int setSerial(SerialStream& ssStream, const string& port);
int sendsms();
};
#endif
In your main.cpp you will need an object of type modem in order to call sendsms() from main():
#include sendSMS.h
class modem{
{
public:
void SendSms();
}
int main(int argc, char **argv) {
modem m;
m.SendSms();
return(0);
}