Error expected for function style cast or type construction

I'm getting the error "Expected '(' for function-style cast or type construction", and have done my best to research the meaning of this error online, but have been unable to find any documentation...

This is a syntax error. Now, non-programmers or amateurs might hear the term syntax error and equate it with a general bug. But in C++ (and other languages) it has a more specific meaning.

There is a language grammar which is a set of rules by which the compiler, at an early stage of translation, breaks up the source code into logical groups. This is before any meaning is ascribed to those groups (that part is sometimes called semantic checking).

The syntax error you saw means that the compiler could not match up the source code to the grammar rules for C++. Precisely because it could not do this — it’s hard for the compiler to know what the programmer intended. So, syntax error messages are often guesses or don’t relate to the programmer intention.

When you see this error, the compiler is suggesting a way of changing the code that would possibly match one of the grammar rules, but that may or may not actually be a good fix in the situation.

So, you can treat this sort of error just as «general syntax error», not worrying too much about the details of the error. To fix it, go back to simpler expressions that you are sure are not syntax errors, and then build up towards what you wanted to write.

An analogy for English language might be the sentence «I the room went of». Imagine some language translation software. This doesn’t match any known sentence structure but what error message can it report? The actual suggestions probably won’t help you to fix the sentence.


In your specific example, there is a syntax error. The g++ error message is different:

error: expected primary-expression before ‘.’ token

where primary-expression is an entry in the C++ grammar. g++ sees the . token and assumes you mean the member access operator. But the grammar says that the left-hand operand of the member access operator must be a primary-expression (and the semantic rules say that this primary-expression denotes the object whose member you want to access).

However in your actual code the left-hand side is (double) boost::integer_traits<unsigned short> which does not match the grammar specification for primary-expression. (In fact it’s a type name). The compiler can’t proceed any further from here so it bails out.

Your compiler also failed to match the code to any grammar rule, but it guessed you were trying to write a function-style cast or type construction.

«Function-style cast» means code like int(5.0), so perhaps it recognized boost::integer_traits<unsigned short> as a type-name, and it guessed that you meant boost::integer_traits<unsigned short>(const_max), i.e. casting some variable const_max to that type.

I’m not sure what your compiler means by «type construction» here.

NB. If you want to know how to fix the actual code in your question, I’d suggest starting a new question where you post the code and error message and ask how to fix the code.

So I’m trying to create a class Room that simulates a hospital room but it keeps giving me an error in my constructor. Sometimes there’s no issue but then it comes back….other user defined objects here include a Patient class that has no problems and a LinkedList template class that also has no issues.

Here’s the header

class Room
{
public:

    Room();
    Room(int);
    static LinkedList<Room> createRooms();

    Patient patient;
    int roomNumber;

    bool operator==(const Room &other) const; //overload ==
    bool operator!=(const Room &other) const; //overload !=
    void operator=(const Room &other) const; //overload =



};

and the cpp

#include "Room.h"

Room::Room();
Room::Room(int n)
{
    roomNumber= n;
    patient= Patient();
}
LinkedList<Room> Room::createRooms() {
    //create rooms up until ROOMS is reached
    LinkedList<Room> roomList;
    for(int i= 1; i < 11; i++){
        Room room= Room(100+i);
        roomList.push(room);
    }
    return roomList;

}
//Overload ==
bool Room::operator==(const Room &other)const{
    //compare each room's room number field
    return (this->roomNumber == other.roomNumber && this->patient == other.patient);

}
//Overload !=
bool Room::operator!=(const Room &other)const{
    return !(this == &other);
}

void Room::operator=(const Room &other)const{
    this->patient= other.patient;
    this->roomNumber= other.roomNumber;
}

the problem is with the Room(int) constructor. Xcode keeps giving me a message saying Expected ‘(‘ for function-style cast or type construction

I have no idea what’s going on

asked Dec 2, 2012 at 23:45

IanPanz's user avatar

2

You clearly forgot to include the header that defines Patient:

 #include "Patient.h"

or similar.

Also,

patient= Patient();

is redundant, the member patient will be value-initialized by default, and

Room::Room();

is not correct — you’re not providing an implementation.

Next, your design seems flawed. You seem to imply that a patient is part of a room, and chose composition to do so. But it’s not. What if the room is empty? Your current design doesn’t yet treat that case.

EDIT: did you mean:

return !(*this == other);

in your overload to operator!=?

answered Dec 2, 2012 at 23:52

Luchian Grigore's user avatar

Luchian GrigoreLuchian Grigore

251k63 gold badges454 silver badges619 bronze badges

3

This looks weird:

   Room::Room();

I think you want this:

   Room::Room() {}

You should probably at least initialize the member variables however instead of having a blank constructor.

answered Dec 2, 2012 at 23:54

Brian Neal's user avatar

Brian NealBrian Neal

31.5k7 gold badges55 silver badges59 bronze badges

1

You may consider to change the following constructor to «explicit» in the header (never abuse «explicit» but sometime is needed)

explicit Room(int);

What if there are in your code places where a class accept both «int» or «const Room&» as constructor parameters?

Assume:

Hospital(int n); //Hospital constructor where n is number of rooms
Hospital(const Room& room); //Hospital constructor, hosptial made initially by only 1 room

In this case without a explicit constructor

Hospital sanGrace(3);

the compiler can’t tell if you intented

Hospital sanGrace(3);

or

Hospital sanGrace(Room(3));

with «explicit» you are forced to write

Hospital sanGrace(Room(3));

if you want to create SanGrace’s Hospital from a room with number 3.

The same applies also for Patient class.

answered Dec 3, 2012 at 0:05

CoffeDeveloper's user avatar

CoffeDeveloperCoffeDeveloper

7,7333 gold badges34 silver badges66 bronze badges

0 / 0 / 0

Регистрация: 16.11.2021

Сообщений: 42

1

01.11.2022, 18:56. Показов 815. Ответов 6


Ошибка «Expected ‘(‘ for function-style cast or type construction» в строчке «widget->setVisible(bool);», причину которой не могу понять.

Код

#include "find_dialog.h"
#include "ui_find_dialog.h"

#include <QDialog>
#include <QLineEdit>
#include <QLabel>
#include <QCheckBox>
#include <QTabWidget>
#include <QPushButton>
#include <QTabWidget>
#include <QWidget>

Find_Dialog::Find_Dialog(QWidget *parent) :
    QDialog(parent),
    ui(new Ui::Find_Dialog)
{
    ui->setupUi(this);
    
    widget->setVisible(bool);                            Expected '(' for function-style cast or type construction

    more_button->setCheckable(true);
}

Find_Dialog::~Find_Dialog()
{
    delete ui;
}

__________________
Помощь в написании контрольных, курсовых и дипломных работ, диссертаций здесь



0



Programming

Эксперт

94731 / 64177 / 26122

Регистрация: 12.04.2006

Сообщений: 116,782

01.11.2022, 18:56

Ответы с готовыми решениями:

[bcc32c Error] Unit2.cpp(57): C-style cast from rvalue to reference type ‘Matrix &’
Здравствуйте, вот какая проблема , писал себе программу на visual studio, написал код, надо создать…

Ошибка CDO:Unable to cast COM object of type ‘System.__ComObject’ to interface type ‘Microsoft.Office.Interop.Outlook.MailItem’
Здаствуйте у меня такая проблема, я получаю сообщения с Outlook’а путем простейших махинаций, когда…

Incorrect Data Type For Operator Or @function: Text Expected
Всем привет!
Есть документ созданный по форме с 3 полями:
Все поля типа Number-Currency…

Error C2440: <function-style-cast>: невозможно преобразовать «unsigned int» в «std::bitset<_Bits>»
С++ Не работает программа! Задание было такое: напишите программу invert(p,x,n), возвращающую…

Работа с Excel. Ошибка invalid variant type cast
Доброго времени суток! перешел с delphi на lazarus, есть проблемы)

procedure…

6

710 / 376 / 116

Регистрация: 30.03.2021

Сообщений: 1,345

01.11.2022, 19:24

2

Цитата
Сообщение от olexxxa
Посмотреть сообщение

widget->setVisible(bool);

true? false? но не bool



0



0 / 0 / 0

Регистрация: 16.11.2021

Сообщений: 42

01.11.2022, 20:49

 [ТС]

3

Нужно создать метод setVisible(bool) для виджета. Как правильно сделать?

Добавлено через 1 минуту
Нужно создать метод setVisible(bool) для виджета. Как правильно сделать?



0



фрилансер

4478 / 3988 / 870

Регистрация: 11.10.2019

Сообщений: 10,503

01.11.2022, 20:52

4

Цитата
Сообщение от olexxxa
Посмотреть сообщение

more_button->setCheckable(true);

почему-то вот тут у тебя всё срослось, а на такой же функции строчкой выше — что произошло то ?

сказали же — true или false. В функцию передаётся значение, а не тип



1



0 / 0 / 0

Регистрация: 16.11.2021

Сообщений: 42

01.11.2022, 21:32

 [ТС]

5

Тогда вопрос. Как сделать так что бы виджет с компонентами отображался на форме после нажатия на кнопку.



0



фрилансер

4478 / 3988 / 870

Регистрация: 11.10.2019

Сообщений: 10,503

01.11.2022, 21:39

6

olexxxa, изначально (в конструкторе диалога) виджет нужно скрыть hide(). Сигнал clicked кнопки обработать — в обработчике показать show() виджет



0



sdf45

710 / 376 / 116

Регистрация: 30.03.2021

Сообщений: 1,345

01.11.2022, 21:42

7

C++ (Qt)
1
2
3
4
connect(button, &QAbstractButton::clicked, this, [this]{
     widget->setVisible(!widget.isVisible());//нажали-показали, еще нажали-спрятали и тд
     //или widget->setVisible(true); // нажали-показали
});



0



Please note, an ordered array is a precondition of the binary search.
To fix your code you might write:

#include <iostream>
#include <algorithm>

bool search(int a[], size_t size, int item)
{
  int beg = 0;
  int end = size-1;

  while (true)
  {
    if ( (beg + 1) >=  end)  
      return (item == a[end] || item ==a[beg]);
    int mid = (beg+end)/2;
    if ( item == a[mid])
      return true; 
    else if ( item < a[mid] )
      end = mid;
    else  
      beg = mid;
  }
}
enum { max_size = 90 };
int main()
{

  int a[max_size];

  int item;
  std::cout << "Enter the item to search for ";
  std::cin >> item;

  size_t size;
  std::cout << "Enter the array size ";
  std::cin >> size;

  if ( size > max_size)
  {
    std::cerr << "wrong inputn";
    return -1;
  }

  std::cout << "Enter the array elementsn";

  for (size_t n = 0; n< size; ++n)
    std::cin >> a[n];

  std::sort( &a[0], &a[size]);

  bool found  = search( a, size, item);
  std::cout << "The item is " << (found ? "foundn" : "not foundn");
}

However, in all programs but exercises, I would use the firepower of the standard C++ library:

#include <iostream>
#include <algorithm>
#include <vector>

int main()
{
  int item;
  std::cout << "Enter the item to search for ";
  std::cin >> item;

  size_t size;
  std::cout << "Enter the array size ";
  std::cin >> size;

  std::cout << "Enter the array elementsn";
  std::vector<int> v;
  v.resize(size);

  for (auto & x : v)
    std::cin >> x;

  sort(v.begin(), v.end());

  auto found =  binary_search(v.begin(), v.end(), item);
  std::cout << "The item is " << (found ? "foundn" : "not foundn");

}

Я не понимаю, почему следующий код не компилируется при использовании приведения типа конструктора:

template<typename T> void foo(const T& t){}

int main(){
foo(unsigned char(0));
}

Ошибки:

  • error: expected primary-expression before ‘unsigned’ для GCC.
  • error: expected '(' for function-style cast or type construction для лязга

Однако эти три синтаксиса верны:

template<typename T> void foo(const T& t){}

int main(){
// c-style cast
foo((unsigned char)0);

// without unsigned
foo(char(0));

// aliased unsigned char
typedef unsigned char uchar;
foo(uchar(0));
}

Таким образом, пространство в типе, очевидно, здесь виновато.

Я думал, что это может быть как-то связано с нашим старым другом самый неприятный разбор, поэтому я попробовал единый синтаксис инициализации, который должен избавиться от такого рода неясностей, но не повезло

template<typename T> void foo(const T& t){}

int main(){
foo(unsigned char{0});
}

Но до сих пор:

  • error: expected primary-expression before ‘unsigned’ для GCC.
  • error: expected '(' for function-style cast or type construction для лязга

Итак, мой вопрос: почему нельзя использовать тип, содержащий пробел, в приведениях в стиле функции? Это не выглядит двусмысленным для меня.

нотаЯ знаю, что могу написать foo<unsigned char>(0), но это не отвечает на вопрос;)

19

Решение

[C++11: 5.2.3/1]: простой тип спецификатор (7.1.6.2) или имяТипа спецификатор (14.6) с последующим в скобках список_выражений создает значение указанного типа с учетом списка выражений. [..]

Изучая грамматику, мы видим, что единственный способ получить unsigned char от простой тип спецификатор производство путем объединения двух из них.

В качестве доказательства опровержения слухов о том, что таблица 10 утверждает обратное, которое я, возможно, сам начал некоторое время назад (: P), заголовок таблицы говорит «спецификатор (ы)» (обратите внимание на необязательное множественное число) и ссылается на проход:

[C++11: 5.2.3/2]: [..] В таблице 10 приведены действительные комбинации из простой типа спецификаторы и типы, которые они указывают. (акцент мой)

Теперь, объединяя простой типа спецификаторы допускается в некоторых случаях:

[C++11: 7.1.6.2/3]: Когда несколько простой типа спецификаторы разрешены, они могут свободно смешиваться с другими Децл-спецификаторы в любом порядке. [..]

… но нет никаких признаков того, что это имеет место с функциональной нотацией, которая ясно заявляет « простой тип спецификатор» — единственное число.

Поэтому GCC правильно, а Visual Studio неправильно.

Что касается Зачем это тот случай … ну, я не знаю. Я подозреваю, что мы могли бы придумать какой-то неоднозначный крайний случай, но Casey В комментариях ниже отмечается, что разрешение этого было бы несовместимо с синтаксисом вызова функции, поскольку в именах функций не должно быть пробелов.

16

Другие решения

Member Avatar

7 Years Ago

Hi all,
Im currently working on a c++ program for school, and I thought it would be nice If i framed the output from a function. I looked all over the web to find a solution to no avail. Im completely stuck. I keep getting 2 errors:

*154:35: error: expected '(' for function-style cast or type construction
        <<"|         "<< (*Function)(int c) <<"         |"<<endl*

and

*166:21: error: cannot take the address of an rvalue of type 'void'
                Problem1Container(&LineLoop(6), choice);
                                  ^~~~~~~~~~~~*

Im not really sure how to proceed. How do I go about fixing these errors? Below is a code snippet for all the relevent code, as well as a screenshot of the code im having issue with.

Thank you!

P.S if there is any other information I should add, let me know. im fairly new to online forums.

void LineLoop(int size)
{
    int x;
    string line;
    for(x = 0; x <= size; x++)
        {
            line = line + "-";
        }
        cout << line <<endl;
}
void Problem1Container(void (*Function) (int c) ,int choice)
{
    cout
    <<"*-----------Output------------*"<<endl
    <<"|                             |"<<endl
    <<"|         "<< (*Function)(int c) <<"         |"<<endl
    <<"|                             |"<<endl
    <<"*-----------Output------------*"<<endl;
}


void Problem1Pics(int choice)
{

    string line;
    if(choice == 1) //lines
    {
        Problem1Container(&LineLoop(6), choice);
    }

screenshot: http://prntscr.com/8rs5dm


Recommended Answers

Show all of the relevant code, including headers (class definitions and function declarations), as well as implementation code for the classes/functions that are failing. You are not providing enough information. We especially need the entire section of code where the errors are occuring and you are only providing segments.

Jump to Post

All 3 Replies

Member Avatar


rubberman

1,355



Nearly a Posting Virtuoso



Featured Poster


7 Years Ago

Show all of the relevant code, including headers (class definitions and function declarations), as well as implementation code for the classes/functions that are failing. You are not providing enough information. We especially need the entire section of code where the errors are occuring and you are only providing segments.

Member Avatar


rubberman

1,355



Nearly a Posting Virtuoso



Featured Poster


7 Years Ago

@alek — no problem! I’ll look at it after it is posted. At earliest it will be this time tomorrow. I don’t get home from work until late.

Member Avatar

7 Years Ago

Here is the full code(keep in mind I have not finished the program yet, im only done with the first problem):

#include <iostream> 
#include <cstdlib>
#include <ctime>
#include <stdlib.h>

using namespace std;

void header()
{
    cout
    <<"********************************************"<<endl
    <<"||  RPS and Dice Game - Alek M----------- ||"<<endl
    <<"********************************************"<<endl;
}

int gamechoice() //chooses what game
{
    cout <<endl
        << "*******************************"<<endl 
        << "* 1. Play Rock/Paper/Scissors *" <<endl
        << "* 2. Play Dice Role Game      *" <<endl
        << "* 3.Exit(If any other input)  *" <<endl
        << "*******************************"<<endl 
        <<"Enter your choice: ";

        return 0;
}


//RPS Game





int RPSProcess(int player, int CPU) //logic for the Rock Paper Scissors
{
    if(player == CPU)
        cout << "You have a tie!" <<endl;
    else if (player == 1 && CPU == 2)
        cout << "You lose!"<< endl;
    else if (player == 2 && CPU == 3)
        cout << "You lose!"<< endl;
    else if (player == 3 && CPU  == 1)
        cout << "You lose!" << endl;
    else
        cout << "You win!" <<endl;

    return 0;



}



void RPSInstructions() //prints instructions for Rock Paper Scissors
{

    cout << endl <<endl
        <<"*****************************" <<endl 
        << "* Rock/Paper/Scissors Game  *"<< endl
        << "* The rules are:            *" <<endl
        << "*tRock beats scissors *" <<endl
        << "*tScissors beat paper *" <<endl
        << "*tPaper beats rock    *" <<endl
        <<"*****************************" <<endl<<endl; 

    cout <<"Game Choices"<<endl
        << "1. Rock"<<endl
        << "2. Paper" <<endl
        <<"3.Scissors"<<endl
        <<"Enter your choice: ";
}


int RPSGenerator() //generates random number 1-3
{
    return (rand()%3)+1;
}


int RPSGame() //Runs the Rock Paper Scissors game
{
    int choice;
    RPSInstructions(); //displays instructions
    cin >> choice;
    choice = tolower(choice);
    int CPU = RPSGenerator(); //sets CPU choice to random generated number
    RPSProcess(choice, CPU); //processes what the result is
return 0;

}




//dice game




void DiceInstructions() //instructions for the dice game
{
    cout << endl 
        << "******************************************************************"<<endl 
        << "* Role Dice Game                                                 *"<< endl
        << "* The rules are                                                  *" << endl
        << "*tYou get 10 points if you get two dice and get a 7.       *" <<endl
        << "*tYou get 5 if you role two dice and get identical numbers.*" <<endl
        << "*tYou get 3 points if you role one dice and get 4.         *" <<endl
        << "******************************************************************"<<endl<<endl;

    cout << "Game Choices:" <<endl
        << "t1. Roll only one dice" <<endl
        << "t2. Roll two dice" <<endl
        << "t3.Quit, Exit your program"<<endl<<endl
        <<"Please Enter your choice: ";
}


void DiceLogic(int D1, int D2) //dice logic
{
    int score; //score for the game 

    if(D2 == 0) //if theres only 1 die, then Die 2 will be 0 by default
        cout << "You rolled a " << D1 <<endl;
    else
        cout << "You rolled a " << D1 << " and a " << D2 <<endl; //else there are two die. 

    if(D1 + D2 == 7)
        score  = 10;
    else if(D1 ==  D2)
        score = 5;
    else if(D2 == 0 && D1 == 4)
        score = 3;
    else
        score = 0;

    cout << "You Scored a "<< score << "!" << endl;


}


int DiceGenerator() // generates random number for dice. 
{
    return (rand()%6)+1;
}

int DiceGame() //runs the dice game.
{
    int choice;
    int dieA, dieB;

    DiceInstructions();
    cin >> choice;

    dieA = DiceGenerator();
    dieB = DiceGenerator();

    if(choice == 1)
        DiceLogic(dieA, 0);
    else if (choice == 2)
        DiceLogic(dieA,dieB);
    else
    {
        cout << "Goodbye!" <<endl;
        exit(0);
    }

    return choice;
}





int programstart() //allows you to choose between games and if you want to play again. 
{
    int choice;
    gamechoice();
    cin >> choice;

    if(choice == 1)
        RPSGame();
    else if(choice == 2)
        DiceGame();
    else
    {
        cout << endl << endl << "Goodbye!" << endl;
        exit(0);
    }

    char playagain;
    cout << "Play again?(y/n): ";
    cin >> playagain;
    playagain = tolower(playagain);

    if(playagain =='y')
        programstart();
    else
        cout <<"Goodbye!";

    return 0;
}




int main() //main function calls the program to start, as well as initilaizes the random generator. 
{
    srand(time(NULL));
    header();
    programstart();

    return 0;
}


Reply to this topic

Be a part of the DaniWeb community

We’re a friendly, industry-focused community of developers, IT pros, digital marketers,
and technology enthusiasts meeting, networking, learning, and sharing knowledge.

  • Forum
  • Beginners
  • Reading in a file (with ints and strings

Reading in a file (with ints and strings) using getline

Hello out there.

I am having trouble reading in a file that holds info about cars (year,make,model). I need to create a vector of objects for each element including one vehicle object. I want to call the fxn that reads in the file and save the file into a vector before I sort and search recursively and iteratively.

my problem is figuring out to use getline. I’ve been reading on what getline is. (i know the name explains what the fxn actually does). If someone can help me out on how to exactly use getline for my code that would be great.

Thank you in advance!!!!

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
//main.cpp
#include <iostream>
#include <vector>
#include <fstream>
#include "Vehicle.h"

using namespace std;

int main() {

    vector<Vehicle>vector1;
    int input;

    ifstream infile;

    readFile(ifstream & infile, vector<Vehicle> & vector1);


//    create menu with while statement
    while (input != 8)
    {
        cout << "1.) Sort by make then search by make recursively." << endl
             << "2.) Sort by model then search by model recursively." << endl
             << "3.) Sort by year then search by year recursively." << endl
             << "4.) Sort by make then search by make iteratively." << endl
             << "5.) Sort by model then search by model iteratively." << endl
             << "6.) Sort by year then search by year iteratively." << endl
             << "7.) Exit" << endl;

//        Receive user input
    cin >> input;

//vehicle in.txt
2010
Ford
Escape
2014
BMW
328xi
2014
BMW
428xi
2012
Ford
Fusion SE
2014
Lamborghini
Gallardo
1967
Pontiac
GTo
1983
DeLorean
DMC-12
1990
Audi
80 Sedan

//functions.cpp

void readFile(ifstream &infile, vector<Vehicle>& vector1)
{
//    Open file
    infile.open("vehiclein.txt");

    int year;
    string make;
    string model;

    if(infile.is_open())
    {
        getline()    //okay now what :)
    }

This will give you an example. It’s similar to what you have given us.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
#include <iostream>
#include <vector>
#include <fstream>
#include <string>

using namespace std;


/* I am going to assume that your Vehicle class looks something like this, and
 * because you didn't provide us your Vehicle.h, I'm going to use the below
 * data structure as an example. */
struct Vehicle {
  int vehicleYear;      // A integer to hold for the vehicle year
  string vehicleName;   // A string for the vehicle name
  string vehicleModel;  // A string for the vehicle model
};

/* Prototype the readFile function here that has a parameter of
 * vector<Vehicle>& */
bool readFile(vector<Vehicle>&);

int main() {
  vector<Vehicle> vehicleObject;
  if(!readFile(vehicleObject))
    return 1;
  else {
    // Simple way of printing the vector
    for(auto iter = vehicleObject.cbegin(); iter!= vehicleObject.cend(); iter++)
      cout << iter->vehicleYear << " "
           << iter->vehicleName << " "
           << iter->vehicleModel << endl;
  }

  return 0;
}

bool readFile(vector<Vehicle>& vehicleObject) {
  /* The reason why I only pass one parameter into this function is because you
   * named this function readFile. Because it's named readFile, why would you
   * want to pass an std::ifstream object into it? Unless you are going to be
   * reading from the file in some other function, let's not pass it the
   * std::ifstream object as a parameter */
  ifstream inFile("veh.txt");
  if(!inFile)
    return false; // If the object was unable to open the file
  else {
    /* We know the text file containing the vehicles looks something like this
     *   Int
     *   String
     *   String
     * So we have to read it as such. */
    Vehicle temp;

    /* EDIT: Forgot to explain this part...
        It basically says while our object inFile can read the from the file and input
        it into our temp data structure, let's also perform the follow - which is getline
        of the vehicle name and model. The ignore() is just a function I like to call to
        prevent getline "skipping over". If you remove the ignore(), things will not read
        properly. */
    while(inFile >> temp.vehicleYear) {
      inFile.ignore();
      getline(inFile, temp.vehicleName);
      getline(inFile, temp.vehicleModel);
      vehicleObject.push_back(temp);
    }
    inFile.close();
    return true;
  }
}

And when I run it, I will get the following:


2010 Ford Escape
2014 BMW 328xi
2014 BMW 428xi
2012 Ford Fusion SE
2014 Lamborghini Gallardo
1967 Pontiac GTo
1983 DeLorean DMC-12
1990 Audi 80 Sedan

Last edited on

So, my Vehicle.h does look something similar to that. I just used a class instead of a struct. As far as my readFile fxn.. I believe i will be passing it into other fxn if you count sorting, search by recursive/iterative fxns as well. Anywho, for my prototype fxn I changed it to the following:

 
    readFile(vector<Vehicle>& vector1);

and when I build my code i keep getting errors on that line. The following error appears:
error: expected ‘(‘ for function-style cast or type construction
readFile(vector<Vehicle>& vector1);
~~~~~~~~~~~~~~~^

do you have an idea why it is telling me this?
Thank you for your help so far

Last edited on

I KNOW WHY IT GIVES ME THAT ERROR… I didn’t write a data type before the function name. :)

I followed your example on using a while statement but i am getting an error for some reason. I used getter and setters for my code in my vehicle.h file.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
class Vehicle {

private:
    int year;
    string make;
    string model;

public:
    Vehicle();  //Default constructor

    Vehicle(int _year, string _make, string _model);

//    Set setters

    void setYear(int _year) {year = _year;}
    void setMake(string _make){make = _make;}
    void setModel(string _model){model = _model;}

//    Set Getters
    int getYear(){return year;}
    string getMake(){return make;}
    string getModel(){return model;}
};

with this said and following your example i set my code to look like the following:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22

bool readFile(vector<Vehicle>& vector1)
{
//    Open file
ifstream infile;

    if(!infile)
        return false;
    else
    {
        Vehicle temp;
        while(infile >> temp.setYear(int _year)
        {
            infile.ignore();
            getline(infile, temp.setMake(string _make));
            getline(infile, temp.setModel(string _model));
            vector1.push_back(temp);
        }
        infile.close();
        return true;
    }

and now the compiler gives me this error:
error: expected ‘(‘ for function-style cast or type construction
while(infile >> temp.setYear(int _year)

any tips on a solution?

EDIT: For some reason, I accidentally removed the part explaining your while loop. Let’s analyze it…

On line 12, while(infile >> temp.setYear(int _year), you are inputting into a function instead of a data type. You are thinking correctly, but the way you are doing it is wrong. You can’t set values to a function, so that’s why we use parameters. The same thing goes with your getline functions. Consider the following:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
bool readFile(vector<Vehicle>& vehicleObject) {
  ifstream inFile("veh.txt");
  if(!inFile)
    return false; // If the object was unable to open the file
  else {
    int year;
    string make, model;
    while(inFile >> year) {
      inFile.ignore();
      getline(inFile, make);
      getline(inFile, model);
      vehicleObject.push_back(Vehicle(year, make, model));


      /*

      You can either push_back by pushing back a constructor which you have
      made, or you can do the following. Give it a try, though I personally prefer the former.

      Vehicle foo;
      foo.setYear(year);
      foo.setMake(make);
      foo.setModel(model);
      vehicleObject.push_back(foo);

      */
    }
    inFile.close();
    return true;
  }
}

Last edited on

It worked! Thank you for your help fiji.

Topic archived. No new replies allowed.

08-19-2014


#1

nlp412 is offline


Registered User


expected for function style cast or type constructor

Hi. I am tackling the following problem: write the function that builds the multiplication table of arbitrary dimensions. I thought I built the function correctly, but when I call it in main, the variables I declare x and y give me the exceptions «expected for function style cast or type constructor». Is there something I am forgetting? It’s really bugging me.

Code:

#include <iostream>


using namespace std;


void create_table(int num_row, int num_col) {
    int **table; //initialize pointer to pointer of int
    table = new int*[num_row]; //create new space for array of int depending on user input
    
    for (int r=0; r<num_row; r++) {
        table[r] = new int[num_col]; //assign pointer to rows of table
    }
   
    for ( int r = 0; r < num_row; r++) {
        for ( int c = 0; c < num_col; c++) {
            **table = r*c;
            cout << **table << "/t";
            
        }
    }
    
    for (int row = 0; row < num_row; row++) {
        delete [] table[row];
        }
    delete [] table;
}








int main[] {
    int y;
    int x;
    cout << "Please enter number of rows: ";
    cin >> y;
    cout << "Please enter number of columns: ";
    cin >> x;
    create_table(y, x);
    return 0;
   
};


@jkuri This the response when I run go build main.go is below. Please clarify where you want me to run the second command. I run it in the same directory as specified in the first line but then says No such file or directory

# gocv.io/x/gocv
Undefined symbols for architecture x86_64:
"cv::GFTTDetector::create(int, double, double, int, bool, double)", referenced from:
_GFTTDetector_Create in features2d.cpp.o
"cv::SimpleBlobDetector::Params::Params()", referenced from:
_SimpleBlobDetector_Create in features2d.cpp.o
"cv::SimpleBlobDetector::create(cv::SimpleBlobDetector::Params const&)", referenced from:
_SimpleBlobDetector_Create in features2d.cpp.o
"cv::FastFeatureDetector::create(int, bool, int)", referenced from:
_FastFeatureDetector_Create in features2d.cpp.o
"cv::AgastFeatureDetector::create(int, bool, int)", referenced from:
_AgastFeatureDetector_Create in features2d.cpp.o
"cv::ORB::create(int, float, int, int, int, int, int, int, int)", referenced from:
_ORB_Create in features2d.cpp.o
"cv::dnn::experimental_dnn_v3::blobFromImage(cv::_InputArray const&, double, cv::Size_<int> const&, cv::Scalar_<double> const&, bool, bool)", referenced from:
_Net_BlobFromImage in dnn.cpp.o
"cv::dnn::experimental_dnn_v3::readNetFromCaffe(cv::String const&, cv::String const&)", referenced from:
_Net_ReadNetFromCaffe in dnn.cpp.o
"cv::dnn::experimental_dnn_v3::readNetFromTensorflow(cv::String const&, cv::String const&)", referenced from:
_Net_ReadNetFromTensorflow in dnn.cpp.o
"cv::dnn::experimental_dnn_v3::Net::forward(cv::String const&)", referenced from:
_Net_Forward in dnn.cpp.o
"cv::dnn::experimental_dnn_v3::Net::setInput(cv::_InputArray const&, cv::String const&)", referenced from:
_Net_SetInput in dnn.cpp.o
"cv::dnn::experimental_dnn_v3::Net::~Net()", referenced from:
_Net_Close in dnn.cpp.o
"cv::KAZE::create(bool, bool, float, int, int, int)", referenced from:
_KAZE_Create in features2d.cpp.o
"cv::MSER::create(int, int, int, double, double, int, double, double, int)", referenced from:
_MSER_Create in features2d.cpp.o
"cv::AKAZE::create(int, int, int, float, int, int, int)", referenced from:
_AKAZE_Create in features2d.cpp.o
"cv::BRISK::create(int, int, float)", referenced from:
_BRISK_Create in features2d.cpp.o
"cv::dnn::experimental_dnn_v3::Net::empty() const", referenced from:
_Net_Empty in dnn.cpp.o
ld: symbol(s) not found for architecture x86_64
clang: error: linker command failed with exit code 1 (use -v to see invocation)

Понравилась статья? Поделить с друзьями:
  • Error expected declaration specifiers or before string constant
  • Error expected declaration or statement at end of input перевод
  • Error executing updater binary in zip twrp что делать 4pda
  • Error executing tk17 engine exe
  • Error executing the specified program realtek что делать