I have a problem in instantiating a new class with another parameter.
My problem is to add something in a QList Asteroids Object. In Qt, I have this error message:
cannot convert 'SettingsAsteroid' to 'SettingsAsteroid*' in assignment
this->settingsAsteroid = SettingsAsteroid();
Below are the relevant files of the class doing it, and I think other classes are not relevant.
Data in GameView.h :
#ifndef GAMEVIEW_H
#define GAMEVIEW_H
#include <QGraphicsView>
#include <QGraphicsItem>
#include <QApplication>
#include <QPushButton>
#include <QList>
#include <QObject>
#include <QString>
#include "Asteroid.h"
#include "SettingsAsteroid.h"
class GameView : public QGraphicsView
{
Q_OBJECT
// Data
int nbAsteroids;
int nbAsteroidsAlive;
SettingsAsteroid* settingsAsteroid;
QList<Asteroid> asteroids;
// Menu
QPushButton *startgame;
// Scène
QGraphicsScene* grfxScene;
public:
GameView();
~GameView();
private slots:
void start();
};
#endif // GAMEVIEW_H
Source code in GameView.c :
#include "GameView.h"
#include <iostream>
GameView::GameView()
{
int nbAsteroids = 0;
int nbAsteroidsAlive = 0;
// data de jeu
this->settingsAsteroid = SettingsAsteroid();
//Scene de debut
this->grfxScene = new QGraphicsScene();
grfxScene->setSceneRect(0,0,800,600);
this->grfxScene->addPixmap(QPixmap(":/images/armageddon.jpg"));
setScene(this->grfxScene);
}
GameView::~GameView(){ }
void GameView::start()
{
this->grfxScene->clear();
int nbAsteroids = 4;
int nbAsteroidsAlive = 4;
int i;
for(i=0;i<nbAsteroids;i++) {
asteroids.append(new Asteroid(settingsAsteroid));
}
}
Constructor of Asteroid.c :
Asteroid::Asteroid(SettingsAsteroid settingsAsteroid)
Based on your error
cannot convert 'SettingsAsteroid' to 'SettingsAsteroid*' in assignment this->settingsAsteroid = SettingsAsteroid();
On the code:
this->settingsAsteroid = SettingsAsteroid();
You are attempting to convert a SettingsAsteroid into a SettingsAsteroid*, that is: a pointer to a SettingsAsteroid object.
Because GameView has a member settingsAsteroid which is a SettingsAsteroid*, you need to give it a pointer to a SettingsAsteroid, not a SettingsObject itself. You can do one of the following:
this->settingsAsteroid = new SettingsAsteroid();
Calling new will allocate memory for the required object (your SettingsAsteroid) and return a pointer to that memory, of type SettingsAsteroid*. Alternatively, if you already have some SettingsAsteroid object you could assign it instead:
SettingsAsteroid sa;
...
this->settingsAsteroid = &sa;
Related
Ok, so I have a struct defined as thus:
#ifndef __STRUCTS_H__
#define __STRUCTS_H__
struct counts {
int views = 0;
int inits = 0;
};
#endif
I have a class that is going to have entirely static methods and variables that are accesable by all classes.
#ifndef __HOLDER_H__
#define __HOLDER_H__
#include "Structs.h"
class Holder
{
public:
static counts menus;
Holder() {
menus = counts();
}
};
#endif
And so I tried to acess this method and the compiler spits out the error "Undefined reference to Holder::menus"
Here is the segment that triggers this (HelloWorldScene.cpp)
#include "HelloWorldScene.h"
#include "SimpleAudioEngine.h"
#include "Holder.h"
#include "Structs.h"
USING_NS_CC;
HelloWorld::HelloWorld(void)
{
//Constructor
Debug::crashLog("**__Menu Deinit__**");
//SUDO Missing stuff
Holder::menus.inits -= 1;
}
Why is it having issues?
in your Holder implementation file you need this:
counts Holder::menus;
if you don't have Holder.cpp file, (and you don't want one) you can put it directly into in HelloWorldScene.cpp.
Dialog.h
#include "WBasic.h"
#include "WButton.h"
#include "WData.h"
#ifndef WDIALOG_H_INCLUDED
#define WDIALOG_H_INCLUDED
class WDialog : public WBasic
{
private:
WButton wB;
WData wD;
public:
//Constructor
WDialog(const int& e = 0, const WButton& = WButton(0,0), const WData& = WData(0,0,0));
~WDialog();
};
#endif // WDIALOG_H_INCLUDED
Dialog.cpp
#include <iostream>
#include "WDialog.h"
WDialog::WDialog(const int& e, const WButton& WBUTTON, const WData& WDATA) :
WBasic(e), wB(WBUTTON), wD(WDATA)
{
}
The code above works great, however I'm trying to make "WButton wB" a vector changing it to"WButton wB[3];"
class WDialog : public WBasic
{
private:
WButton wB[3];
WData wD;
};
But then I've no idea how deal with the Constructor.
You can use vector to solve this problem.
I have written a small example below.
#include <iostream>
#include <vector>
using namespace std;
class A{
};
class B{
public:
B():vec (4,A())
{
}
private :
vector<A> vec;
};
int main() {
// your code goes here
B obj();
return 0;
}
You can observe how I have initialized vector vec with three class A object.
In my opinion if you can (your compiler support C++11) prefer std::array
#include <array>
std::array<WButton, 3> wB;
Then in your contructor use an initializer list:
WBasic(e),
wB{WButton(...), WButton(...), WButton(...)},
wD(WDATA)
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/
I'll try and explain this the best I can...
Basically, I'm writing this program for a GBA game and I'm trying to change a member variable of a struct instance from within a class. This is the code, omitting unnecessary parts:
player.cpp
#include "player.h" // Line 1
#include "BgLayerSettings.h"
player::player(){
x = 16;
y = 16;
health = 5;
direction = LEFT;
dead = false;
}
player::~player(){
}
// Omitted unrelated code
void player::ScrollScreen(){ // Line 99
if(x>((240/2)-8)){
BACKGROUND_2.h_offset += x-((240/2)-8);
}
}
player.h
#include <stdint.h> // Line 1
#include <stdlib.h>
#include <string.h>
#include "gba.h"
#include "font.h"
#pragma once
class player {
public:
player();
~player();
unsigned int x;
unsigned int y;
void ScrollScreen();
};
BgLayerSettings.cpp
#include "player.h" // Line 1
#include "BgLayerSettings"
BgLayerSettings::BgLayerSettings(){
charblock = 0;
screenblock = BLANK;
v_offset = 0;
h_offset = 0;
}
BgLayerSettings::~BgLayerSettings(){
}
BgLayerSettings.h
#include <stdint.h> // Line 1
#include <stdlib.h>
#include <string.h>
#include "gbs.h"
#include "font.h"
#pragma once
enum BACKGROUND {bg0=0, bg1, bg2, bg3, bg4, bg5, bg6, bg7,
bg8, bg9, bg10, bg11, bg12, bg13, bg14, bg15,
bg16, bg17, bg18, bg19, bg20, bg21, bg22, bg23,
bg24, bg25, bg26, bg27, bg28, DUNGEON_1, DUNGEON_FLOOR, BLANK,
};
struct BgLayerSettings {
public:
BgLayerSettings();
~BgLayerSettings();
unsigned int charblock;
BACKGROUND screenblock;
int v_offset;
int h_offset;
};
main.cpp
#include "player.h" // Line 1
#include "BgLayerSettings.h"
player Player;
BgLayerSettings BACKGROUND_0;
BgLayerSettings BACKGROUND_1;
BgLayerSettings BACKGROUND_2;
BgLayerSettings BACKGROUND_3;
// Omitted unrelated code
Essentially I'm trying to change the variable h_offset of the object BACKGROUND_2 from within the player class.
When I try to compile this, I receive this error:
player.cpp: In member function 'void player::ScrollScreen()':
player.cpp:101:3: error: 'BACKGROUND_2' was not declared in this scope
make: *** [player.o] Error 1
No matter what I try, I cannot get past this error. Anyone able to shed some light on this for me?
Thanks in advance.
It doesn't look like Player.cpp, specifically this line...
BACKGROUND_2.h_offset += x-((240/2)-8);
can see the instance of BACKGROUND_2. If you are instantiating it in main.cpp then there'd be no way for Player.cpp to see that during the build. You should pass whatever background you want to change into the function as a reference and change it from the main.cpp. Something like this instead...
void player::ScrollScreen( BgLayerSettings &bg ){ // Line 99
if(x>((240/2)-8)){
bg.h_offset += x-((240/2)-8);
}
}
Your main.cpp would be something like this...
player1.ScrollScreen( BACKGROUND_2 );
I have 2 Qt programs that are basically identical, I copied the code from one of them to the other to modify it and save it as a new project, now the second one doesn't run and gives a bunch of errors which don't make sense because the other one runs and they are the same where the errors are coming up. Here is the code:
#ifndef FILM_H
#define FILM_H
#include <QWidget>
#include <QString>
#include <QDate>
class Film: public QObject{
Q_OBJECT
Q_PROPERTY( QString title READ getTitle WRITE setTitle);
Q_PROPERTY( int duration READ getDuration WRITE setDuration);
Q_PROPERTY( QString director READ getDirector WRITE setDirector);
Q_PROPERTY( QDate releaseDate READ getReleaseDate WRITE setReleaseDate);
public:
Film(QString t,int dur,QString dir,QDate r);
Film();
void setTitle(QString t);
void setDuration(int dur);
void setDirector(QString dir);
void setReleaseDate(QDate r);
QString getTitle() const;
int getDuration() const;
QString getDirector() const;
QDate getReleaseDate() const;
QString toString();
private:
QString m_title;
int m_duration;
QString m_director;
QDate m_releaseDate;
};
#endif // FILM_H
#ifndef FILMWRITER_H
#define FILMWRITER_H
#include "Film.h"
#include <QtGui>
#include <QFile>
class FilmWriter{
public:
void accessFilm(Film& f);
};
#endif // FILMWRITER_H
#ifndef FILMINPUT_H
#define FILMINPUT_H
#include <QMainWindow>
#include "Film.h"
#include "FilmWriter.h"
#include <QLabel>
#include <QTextEdit>
#include <QPushButton>
namespace Ui {
class FilmInput;
}
class FilmInput : public QMainWindow
{
Q_OBJECT
public:
explicit FilmInput(QWidget *parent = 0);
~FilmInput();
void obtainFilmData(Film& f);
void saveFilm(Film& f);
public slots:
void getFilm();
private:
Ui::FilmInput *ui;
//widgets
QMainWindow* window;
QLabel* infoLabel;
QLabel* titleLabel;
QLabel* durationLabel;
QLabel* directorLabel;
QLabel* relDateLabel;
QTextEdit* titleEdit;
QTextEdit* durationEdit;
QTextEdit* directorEdit;
QTextEdit* relDateEdit;
QPushButton* saveBtn;
QPushButton* cancelBtn;
Film f;
//sets up gui and connects signals and slots
void setUpGui();
};
#endif // FILMINPUT_H
#include "Film.h"
#include <QDate>
#include <QString>
Film::Film(QString t,int dur,QString dir,QDate r):m_title(t),m_duration(dur),m_director(dir),m_releaseDate(r){
}
Film::Film(){
}
void Film::setTitle(QString t){
m_title = t;
}
void Film::setDuration(int dur){
m_duration = dur;
}
void Film::setDirector(QString dir){
m_director = dir;
}
void Film::setReleaseDate(QDate r){
m_releaseDate = r;
}
QString Film::getTitle() const{
return QString("%1").arg(m_title);
}
int Film::getDuration() const{
return m_duration;
}
QString Film::getDirector() const{
return QString("%1").arg(m_director);
}
QDate Film::getReleaseDate() const{
return m_releaseDate;
}
QString Film::toString()
{
return m_title + " " + m_duration + " " + m_director + " " + m_releaseDate.toString();
}
#include "FilmWriter.h"
#include <QtGui>
#include <QFileDialog>
#include <QFile>
#include <QMessageBox>
#include <QObject>
#include <QTextStream>
void FilmWriter::accessFilm(Film& f){
QVariant v1 = f.property("title");
QVariant v2 = f.property("duration");
QVariant v3 = f.property("director");
QVariant v4 = f.property("releaseDate");
QString str = v1.toString() +" "+ v2.toString() +" "+ v3.toString() +" "+ v4.toString();
QMessageBox msgBox;
msgBox.setText(str);
msgBox.exec();
}
#include "filminput.h"
#include "ui_filminput.h"
#include <QtGui>
#include "Film.h"
#include "FilmWriter.h"
#include <QTextEdit>
#include <QDate>
#include <QString>
FilmInput::FilmInput(QWidget *parent) :
QMainWindow(parent),
ui(new Ui::FilmInput)
{
ui->setupUi(this);
setUpGui();
}
FilmInput::~FilmInput()
{
delete ui;
}
void FilmInput::setUpGui(){
//initialise widgets
infoLabel = new QLabel("Please enter film data which will be saved to a file",this);
titleLabel = new QLabel("Film Title",this);
durationLabel = new QLabel("Film Duration",this);
directorLabel = new QLabel("Film Director",this);
relDateLabel = new QLabel("Film Release Date",this);
titleEdit = new QTextEdit(this);
durationEdit = new QTextEdit(this);
directorEdit = new QTextEdit(this);
relDateEdit = new QTextEdit(this);
saveBtn = new QPushButton("Save Film",this);
cancelBtn = new QPushButton("Cancel",this);
//set layout
QFormLayout* layout = new QFormLayout();
layout->addWidget(infoLabel);
layout->addWidget(titleLabel);
layout->addWidget(titleEdit);
layout->addWidget(durationLabel);
layout->addWidget(durationEdit);
layout->addWidget(directorLabel);
layout->addWidget(directorEdit);
layout->addWidget(relDateLabel);
layout->addWidget(relDateEdit);
layout->addWidget(saveBtn);
layout->addWidget(cancelBtn);
this->ui->widget->setLayout(layout);
this->setWindowTitle("Film Archive");
connect(saveBtn,SIGNAL(clicked()),this, SLOT(getFilm()));
connect(cancelBtn,SIGNAL(clicked()),this,SLOT(close()));
}
void FilmInput::getFilm(){
Film f1(titleEdit->toPlainText(),durationEdit->toPlainText().toInt() ,directorEdit->toPlainText(),
QDate::fromString(relDateEdit->toPlainText(),"dd/MM/YYYY"));;
obtainFilmData(f1);
}
void FilmInput::obtainFilmData(Film &f){
FilmWriter f2;
f2.accessFilm(f);
}
#include <QtGui/QApplication>
#include "filminput.h"
int main(int argc, char *argv[])
{
QApplication a(argc, argv);
FilmInput w;
w.show();
return a.exec();
}
the error dump:
..\Ass1Q2\filminput.cpp: In constructor 'FilmInput::FilmInput(QWidget*)':
..\Ass1Q2\filminput.cpp:12: error: invalid use of incomplete type 'struct Ui::FilmInput'
..\Ass1Q2\/filminput.h:12: error: forward declaration of 'struct Ui::FilmInput'
..\Ass1Q2\filminput.cpp:14: error: invalid use of incomplete type 'struct Ui::FilmInput'
..\Ass1Q2\/filminput.h:12: error: forward declaration of 'struct Ui::FilmInput'
..\Ass1Q2\filminput.cpp: In destructor 'virtual FilmInput::~FilmInput()':
..\Ass1Q2\filminput.cpp:20: warning: possible problem detected in invocation of delete operator:
..\Ass1Q2\filminput.cpp:20: warning: invalid use of incomplete type 'struct Ui::FilmInput'
..\Ass1Q2\/filminput.h:12: warning: forward declaration of 'struct Ui::FilmInput'
..\Ass1Q2\filminput.cpp:20: note: neither the destructor nor the class-specific operator delete will be called, even if they are declared when the class is defined.
..\Ass1Q2\filminput.cpp: In member function 'void FilmInput::setUpGui()':
..\Ass1Q2\filminput.cpp:50: error: invalid use of incomplete type 'struct Ui::FilmInput'
..\Ass1Q2\/filminput.h:12: error: forward declaration of 'struct Ui::FilmInput'
mingw32-make[1]: Leaving directory `C:/Unisa/COS3711/assignments/Ass1Q2-build-desktop'
mingw32-make: Leaving directory `C:/Unisa/COS3711/assignments/Ass1Q2-build-desktop'
mingw32-make[1]: *** [debug/filminput.o] Error 1
mingw32-make: *** [debug] Error 2
The process "C:/Qt/2010.04/mingw/bin/mingw32-make.exe" exited with code %2.
Error while building project Ass1Q2 (target: Desktop)
When executing build step 'Make'
You copied the code, but not pro file. So, you may miss to add UI file to profile, to invoc UI compiler to generate "ui_FileInput.h" source. Please copy UI file and update .pro file with FORMS += FileInput.ui may solve your problem. To know better you can comment "ui_FileInput.h" and see the behaviour.