I am working on a project for my intro to c++ class which is to build a program to calculate various statistics. I have the calculations down, but our professor wants us to use std::istream
to collect the input from a file. The program will keep collecting information from the file until it reaches an End of File marker. I am very unfamiliar with the way std::istream
works and I keep encountering this error when I try to compile.
main.cpp:5:10: error: call to non-static member function without an
object argument stats::getInput(std::cin);
Here is my stats.cpp file:
#include "stats.h"
#include <vector>
#include <cstdlib>
#include <iostream>
stats::stats(){
}
std::vector <double> stats::getInput(std::istream& input_stream){
std::vector <double> stream;
double x;
while(input_stream){
input_stream >> x;
// std::cout << "your list of numbers is: " << x << std::endl;
if(input_stream){
stream.push_back(x);
}
}
return stream;
}
Here is my header file:
#ifndef _STATS_
#define _STATS_
#include <vector>
#include <cstdlib>
class stats{
public:
stats();
std::vector <double> getInput(std::istream& input_stream);
private:
};
#endif
and here is my main.cpp file:
#include "stats.h"
#include <iostream>
int main(){
stats::getInput(std::cin);
}
Like I said, I am a beginner in c++ so the answer is probably fairly simple, but c++ is vastly different than Python. I have seen similar questions, but none of them have helped me figure it out.
Thanks
MetMark 6 / 3 / 0 Регистрация: 04.05.2018 Сообщений: 398 |
||||||||||||
1 |
||||||||||||
Ошибка при вызове метода06.07.2019, 20:42. Показов 3786. Ответов 17 Метки нет (Все метки)
Доброго времени суток.
В этом методе diagonalA_C отрисовывается диагональ А-С с помощью QPainter, но отсюда он не вызывается… Шо не так? Error mainwindow.cpp:331:40: error: call to non-static member function without an object argument Этот метод я расписал в public: в class DraftsmanCube. Т.е. там и сам метод объявлен и тело метода там же написал P.S. Дописал в DraftsmanCube.h к void diagonal… «static», у указателя убрал (this) (потому что на него ругался…) и ошибки пропали, но он не рисует теперь… На сколько я понимаю сейчас, весь косяк в том, что он не понимает на чем ему рисовать, но без static в файле mainwindow.cpp метод не вызывается…
__________________
0 |
peter_irich 308 / 168 / 46 Регистрация: 18.10.2017 Сообщений: 1,585 |
||||||||||||
06.07.2019, 21:36 |
2 |
|||||||||||
Вы посмотрите примеры, как работает QPainter.
либо
а если не this, то на чём он рисует, а после завершения рисования надо вызвать
0 |
6 / 3 / 0 Регистрация: 04.05.2018 Сообщений: 398 |
|
06.07.2019, 21:41 [ТС] |
3 |
peter_irich, Перечитайте сообщение, я там ваше предложение объяснил
0 |
308 / 168 / 46 Регистрация: 18.10.2017 Сообщений: 1,585 |
|
06.07.2019, 21:53 |
4 |
Да, действительно, но почему не объявить и создать эту функцию в mainwindow.cpp?
0 |
MetMark 6 / 3 / 0 Регистрация: 04.05.2018 Сообщений: 398 |
||||
06.07.2019, 22:47 [ТС] |
5 |
|||
peter_irich, DraftsmanCube — это отдельный собственный Widget у которого не функция, а метод diagonalA_C Немного поразбирался в static и понял, что он сюды не подходит. Мне нужно вызвать метод класса DraftsmanCube::diagonalA_C(), чтобы он выполнился для уже существующего объекта который называется у меня *Cube. Как направить этот метод именно для этого объекта я не понимаю Решение — написал такую строчку, но от этого метод не начал рисовать…
В отладчике посмотрел, через эту строчку проходит, все норм, но почему-то не рисует… На сколько я понимаю, нужно как-то в методе указать, что надо рисовать на *Cube, но только как?
0 |
308 / 168 / 46 Регистрация: 18.10.2017 Сообщений: 1,585 |
|
06.07.2019, 23:16 |
6 |
Я не знаю, в чём заключается различие между функцией и методом, но в любом случае можно вызвать
0 |
MetMark 6 / 3 / 0 Регистрация: 04.05.2018 Сообщений: 398 |
||||||||
06.07.2019, 23:33 [ТС] |
7 |
|||||||
peter_irich, Вы все равно не так немного поняли, но я использовал вашу идею. Выдало в консоль вот это
а в методе написал:
И в качестве родителя QPainter принимает &ptr Случайно никаких методов перерисовки моего Widget-а вызывать не надо?
0 |
308 / 168 / 46 Регистрация: 18.10.2017 Сообщений: 1,585 |
|
07.07.2019, 08:41 |
8 |
Я же всё равно не знаю, что такое Cube, т.е. что представляет собой его класс. Если виджет находится на экране, то принудительно его перерисовывать не надо, для него достаточно,
0 |
Анна по жизни 283 / 172 / 62 Регистрация: 13.03.2019 Сообщений: 416 |
||||
07.07.2019, 11:54 |
9 |
|||
Отрисовка должна происходить в методе DraftsmanCube:aintEvent(), следовательно, именно там должен вызываться метод diagonalA_C() . В mainWindow должно указать конкретному экземпляру:»С этого момента ты должен отрисовывать диагональ АС», но не вызывать его метод отрисовки (тем более, в этом случае диагональ отрисуется один раз, а при следующем вызове DraftsmanCube:aintEvent() она затрётся) У DraftsmanCube должен быть метод, через который у экземпляра взведётся.снимается флажок, ответственный за отрисовку диагонали. А сама отрисовка должна происходить в paintEvent().
0 |
308 / 168 / 46 Регистрация: 18.10.2017 Сообщений: 1,585 |
|
07.07.2019, 16:35 |
10 |
У меня в одной программе может использоваться либо свой paintEvent(), либо paintEvent() в другом виджете,
0 |
6 / 3 / 0 Регистрация: 04.05.2018 Сообщений: 398 |
|
07.07.2019, 17:38 [ТС] |
11 |
Анна по жизни, После создания объекта и расположения на форме у меня отрисовывается моя фигура в :aintEvent(QPaintEvent *); Если в :aintEvent(QPaintEvent *); произойдут изменения он Painter перерисует?
С этого момента ты должен отрисовывать диагональ АС virtual void paintEvent(QPaintEvent *); — находится в protected, доступ получить не могу.
0 |
308 / 168 / 46 Регистрация: 18.10.2017 Сообщений: 1,585 |
|
07.07.2019, 18:13 |
12 |
Я удивляюсь, вы берётесь создавать программы в Qt и не знаете, что делать с функциями из protected. Выше ошибка, должно быть так:
0 |
MetMark 6 / 3 / 0 Регистрация: 04.05.2018 Сообщений: 398 |
||||
07.07.2019, 18:40 [ТС] |
13 |
|||
Проще говоря. Как вызвать из файла .cpp класса MainWindow, virtual void paintEvent(QPaintEvent *); который объявлен в protected класса DraftsmanCube?
Я удивляюсь, вы берётесь создавать программы в Qt и не знаете, что делать с функциями из protected. Объясните, ну пожааааааалуйста, очень вас прошу. Не понимаю то, что написано в примерах Единственное что я могу предположить, это то, что мне нужно унаследовать MainWindow от DraftsmanCube и тогда я смогу вызвать все что угодно из protected В mainwindow.cpp у меня есть следующие строчки:
0 |
308 / 168 / 46 Регистрация: 18.10.2017 Сообщений: 1,585 |
|
07.07.2019, 19:30 |
14 |
Неправильно предполагаете. Возьмите толстую книгу, лучше в электронном виде, и почитайте,
0 |
6 / 3 / 0 Регистрация: 04.05.2018 Сообщений: 398 |
|
07.07.2019, 19:37 [ТС] |
15 |
peter_irich, Про QPainter и про QPaintEvent я читал уже в этой книге. Можете просто написать, как в моем случае должно сработать? Пожалуйста
0 |
308 / 168 / 46 Регистрация: 18.10.2017 Сообщений: 1,585 |
|
07.07.2019, 20:14 |
16 |
Я не знаю, как у вас должно сработать, т.к. не знаю вашей программы.
0 |
283 / 172 / 62 Регистрация: 13.03.2019 Сообщений: 416 |
|
08.07.2019, 11:29 |
17 |
virtual void paintEvent(QPaintEvent *); — находится в protected, доступ получить не могу. И не надо. Установи флажок, по которому Cube будет рисовать диагональ, и вызови Cube->update(). Добавлено через 7 минут
0 |
6 / 3 / 0 Регистрация: 04.05.2018 Сообщений: 398 |
|
08.07.2019, 11:53 [ТС] |
18 |
Анна по жизни, Да, я новую тему создал и уже догадался. Спасибо вам большое! Есть же добрые люди!!! Спасибо огромное вам!
0 |
IT_Exp Эксперт 87844 / 49110 / 22898 Регистрация: 17.06.2006 Сообщений: 92,604 |
08.07.2019, 11:53 |
18 |
error: calls a non-static member function with no object arguments.
this error occurs because the class is not instantiated with .
Take a chestnut, for example:
class Student
{
public:
int getAge();
};
The reason for this error may be that when you call the function getAge(), you are doing this:
Student::getAge();
Or do it this way:
Student.getAge();
This means that the member function is called without instantiating the class Student.
Fix one: Instantiate an object first
Student XiaoWang;
int age = XiaoWang.getAge();
Correction 2: Declare member functions as static functions
class Student
{
public:
static int getAge();
};
Student::getAge();
Take chestnuts, for example:
QDir::mkpath(Path);
Error: Calling a non-static member function with no object arguments.
the reasons for this error is that the class does not instantiate and call mkpath function need to first class instantiation,
to:
QDir tempDir;
tempDir.mkpath(Path);
That’s right.
If you write your own class, you can also add the static keyword before the function’s declaration in the class body to declare the function as a static member and call it without instantiation.
such as:
QMessageBox::warning(this,tr("Warning"),tr("No Exist"));
Static member functions can be called directly with “ class :: function name
“.
Read More:
This topic has been deleted. Only users with topic management privileges can see it.
Hello everyone,
I am trying to implement Signal&Slots. But I am getting the Error: «call to non static member function without an object argument «
mainwindow.cpp
void MainWindow::on_Button_clicked()
{
addressEntry *name = new addressEntry();
name->setName(ui->lineName->text());
connect(addressEntry::setName(name), SIGNAL(entry(QString)), addressReaderWriter::Write(name), SLOT(Write(QString)));
}
addressEntry.cpp
void addressEntry::setName(QString name)
{
mName = name;
qDebug() << "setName";
emit entry(name);
}
QString addressEntry::getName()
{
return mName;
}
addressReaderWriter.cpp
void addressReaderWriter::Write(QString name){
name.getName();
}
Hope Someone can help.
Hi,
Your connect statement is wrong.
setName is a member function that you are calling like if it was a static function.
The first and third parameters of connect should be objects.
@SGaist Thank you for your reply. I understand the problem, but could you tell me how I can solve it?
My goal is it to transfer the variable «name->setName(ui->lineName->text());»from void MainWindow::on_btnAdd_clicked() to void addressReaderWriter::Write(QString name){
by using Signal&Slots
Dis you read the documentation of the method ?
The first parameter shall be the object that will emit the signal and the third the object that will have the slot activated.
@SGaist Yes I read it, but I am having trouble to implement it correctly
@Chaki
The first and third parameter needs to be a pointer to your sender / receiver object.
What you did can not work and I also think you’ve put it in the wrong place.
@Chaki said in call to non static member function without an object argument:
but I am having trouble to implement it correctly
Then please show what you have now…
@jsulm currently I am trying:
mainwindow.cpp:
void MainWindow::on_btnAdd_clicked()
{
addressEntry *name = new addressEntry();
name->**setName**(ui->lineEdit->text());
connect(&name, SIGNAL(addressEntry::entry(QString)), addressReaderWriter::Write(name), SLOT(addressReaderWriter::Write(QString)));
}
addressentry.h:
signals:
void entry(QString name);
addressentry.cpp:
void addressEntry::setName(QString name)
{
mName = name;
emit entry(name);
}
addressReaderWriter.h:
public slots:
void Write(QString);
addressReaderWriter.cpp
void addressReaderWriter::Write(QString name){
name.getName();
}
Your signal/slot signatures in the connect() are wrong. Please read https://doc.qt.io/qt-5/signalsandslots.html before using something.
@Christian-Ehrlicher I know that the connect is wrong and I have read the Docu, but I am having trouble using it correctly
There is so much wrong in your code I don’t even know where to start. I would suggest you to start with one of the Qt examples and learn c++ — sorry.
@Chaki said in call to non static member function without an object argument:
I have read the Docu
If you did then why are you still doing it wrongly? Your code does not even make sence to be honest.
connect(name, &addressEntry::entry, addressReaderWriterInstancePtr, &addressReaderWriter::Write);
addressReaderWriterInstancePtr would be a pointer to an instance of addressReaderWriter which you want to react on the signal.
This post is deleted!
@MalitheBIG said in call to non static member function without an object argument:
Thats not how you treat new useres who try to get into QT.
Before you learn Qt you have to learn c++, thats the reality — sorry.
This post is deleted!
This post is deleted!
@MalitheBIG Da stimme ich Ihnen zu
@MalitheBIG That’s true, maybe try and help him instead of just calling him stupid
This post is deleted!
I have spent a few hours working on this and am finally down to three errors «call to non-static member function without an object argument. The errors are in both of the display functions. Any help is greatly appreciated
|
|
Как описано Вот:, Вы можете подключить сигнал к простой функции, например так:
connect(
sender, &Sender::valueChanged,
someFunction
);
Вот моя программа:
#include <QCoreApplication>
#include <QNetworkAccessManager>
#include <QNetworkReply>
#include <QNetworkRequest>void handleReply(QNetworkReply *reply)
{
QString replyStr = reply->readAll();
}
int main(int argc, char *argv[])
{
QCoreApplication a(argc, argv);
QNetworkAccessManager manager;
connect(&manager, &QNetworkAccessManager::finished(QNetworkReply*), handleReply(QNetworkReply*));
return a.exec();
}
Однако я получаю несколько ошибок:
main.cpp:18: error: call to non-static member function without an object argument
connect(&manager, &QNetworkAccessManager::finished(QNetworkReply*), handleReply(QNetworkReply*));
~~~~~~~~~~~~~~~~~~~~~~~^~~~~~~~
main.cpp:18: error: 'QNetworkReply' does not refer to a value
connect(&manager, &QNetworkAccessManager::finished(QNetworkReply*), handleReply(QNetworkReply*));
^
main.cpp:18: error: expected expression
connect(&manager, &QNetworkAccessManager::finished(QNetworkReply*), handleReply(QNetworkReply*));
^
main.cpp:18: error: 'QNetworkReply' does not refer to a value
connect(&manager, &QNetworkAccessManager::finished(QNetworkReply*), handleReply(QNetworkReply*));
^
/usr/include/x86_64-linux-gnu/qt5/QtNetwork/qnetworkreply.h:62: declared here
class Q_NETWORK_EXPORT QNetworkReply: public QIODevice
main.cpp:18: error: expected expression
connect(&manager, &QNetworkAccessManager::finished(QNetworkReply*), handleReply(QNetworkReply*));
^
^
Буду признателен за любую помощь. Спасибо.
0
Решение
При использовании нового синтаксиса соединения указывать тип аргументов не обязательно, поэтому просто используйте:
#include <QCoreApplication>
#include <QNetworkAccessManager>
#include <QNetworkReply>
#include <QNetworkRequest>
#include <QDebug>
static void handleReply(QNetworkReply *reply)
{
QString replyStr = reply->readAll();
// do stuff
qDebug()<< replyStr;
reply->deleteLater();
}
int main(int argc, char *argv[])
{
QCoreApplication a(argc, argv);
QNetworkAccessManager manager;
QObject::connect(&manager, &QNetworkAccessManager::finished, &handleReply);
manager.get(QNetworkRequest(QUrl("https://www.google.com")));
return a.exec();
}
Замечания:
Вы должны использовать только connect(...)
если вы находитесь внутри класса, который наследует от QObject
, в случае основного вы должны использовать QObject::connect(...)
1
Другие решения
Других решений пока нет …