[Solved] mainwindow.cpp:23: error: C2678: binary '<<' : no operator found which takes a left-hand operand of type 'QTextStream *' (or there is no acce
-
@#include "mainwindow.h"
#include "ui_mainwindow.h"
#include <QTextStream>
#include <QFile>MainWindow::MainWindow(QWidget *parent) :
QMainWindow(parent),
ui(new Ui::MainWindow)
{
ui->setupUi(this);QFile *outfile = new QFile; outfile->setFileName("test.txt"); outfile->open(QIODevice::ReadWrite); QTextStream* out = new QTextStream(outfile); QString str = "test"; out << str;
}
MainWindow::~MainWindow()
{
delete ui;
}@
What did i do wrong? -
Hi,
You are using pointers where you shouldn't and thus you have two memory leaks and an opened file that you can't close.
@
QFile outfile("test.txt");
if (outfile.open(QIODevice::ReadWrite)) {
QTextStream out(outfile);
QString str = "test";
out << str;
} else {
// output error
// show dialog etc.
}
@ -
Hi,
I did this for example and in real code i want to open file in the constructor and then use that file in the slot. So i tried to do this with pointers but can't understand why this don't work.
It looks like this :
mainwindow.h
@#ifndef MAINWINDOW_H
#define MAINWINDOW_H#include <QMainWindow>
#include <QTextStream>
#include <QFile>namespace Ui {
class MainWindow;
}class MainWindow : public QMainWindow
{
Q_OBJECTpublic:
explicit MainWindow(QWidget *parent = 0);
~MainWindow();
private slots:
void on_action_2_triggered();
private:
QFile *file;
QTextStream *fileStrem;
Ui::MainWindow *ui;
};#endif // MAINWINDOW_H@
mainwindow.cpp
@#include "mainwindow.h"
#include "ui_mainwindow.h"MainWindow::MainWindow(QWidget *parent) :
QMainWindow(parent),
ui(new Ui::MainWindow)
{
ui->setupUi(this);file = new QFile; file->setFileName("test.txt"); file->open(QIODevice::ReadWrite); FileStrem = new QTextStream(file);
}
MainWindow::~MainWindow()
{
delete ui;
}
void MainWindow::on_action_2_triggered()
{
QString str = "some text";
FileStrem << str;
}@ -
Because a "pointer":http://www.cplusplus.com/doc/tutorial/pointers/ to an object is not the same as an object directly. However, there's still no reason to use pointers in your case.