I'm new in C++
I try to pass array as parameters I can't find a solution.
Here's my code :
My Header code
autobus.h
#ifndef autobus_H
#define autobus_H
#include <iostream>
using namespace std;
class autobus{
public :
int placeautobus[2] [40];
autobus();
void affichageTicket();
int calculdesplaces(int, int);
};
#endif
Bus.cpp
#include <iostream>
#include "autobus.h"
autobus::autobus(){
int i,j;
for (i=0;i<2;i++) {
for (j=0;j<40;j++)
placeautobus[i][j] = 0;
}
};
void autobus::affichageTicket()
{
}
int autobus::calculdesplaces(int typeautobus, int *placeautobus[2][40]){
int placenumero;
for (int place = 0; place < 40; place++){
if ( placeautobus[typeautobus][place] ==0) {
placenumero = place+1;
cout <<"Places : "<< placenumero <<endl;
}
}
return placenumero;
}
finally my main.cpp
#include <cstdlib>
#include <iostream>
#include "autobus.h"
using namespace std;
int main()
{
int TypeAutobus;
autobus *choixautobus = new autobus();
cout << "1 for smoking bus" << endl;
cout << "2 for non-smoking bus" << endl;
cin >> TypeAutobus;
choixautobus->calculdesplaces(TypeAutobus, choixautobus->placeautobus[2][40]);
system("PAUSE");
return EXIT_SUCCESS;
}
Everything works, but when I add this line in my main.cpp :
choixautobus->calculdesplaces(TypeAutobus, choixautobus->placeautobus[2][40]);
I have an error, I try many things.
I just want to call my function calculdesplaces with the variable : choixautobus having array placeautobus.
Can someone know how to do this.
thanks
Like others have said already, the code you have now shouldn't compile right now because of the declaration and definition mismatch for calculdesplaces.
You shouldn't need to pass the placeautobus array at all since it is a member of the autobus class. Just delete your 2nd argument from calculdesplaces and you should be able to do what you want.
int autobus::calculdesplaces(int typeautobus){
int placenumero;
for (int place = 0; place < 40; place++){
if ( placeautobus[typeautobus][place] ==0) {
placenumero = place+1;
cout <<"Places : "<< placenumero <<endl;
}
}
return placenumero;
}
In your class declaration, you need to specify the correct array pointer type for the second parameter of calculdesplaces():
class autobus{
public :
autobus();
void affichageTicket();
int calculdesplaces(int typeautobus, int (*placeautobus)[40]);
int placeautobus[2][40];
};
This declares, that you are passing a pointer to an array of 40 int elements. This is precisely the type to which the 2D array int placeautobus[2][40]; decays when you use its name: When you mention the name of an array, the array name decays into a pointer to its first element. In the case of an array of type int ()[2][40], that is a pointer to the first line array (type is int (*)[40]).
Note that the parentheses in int (*placeautobus)[40] are very important: the array subscript operator [] has a higher precedence than the dereferencing operator *, so int (*placeautobus)[40] means something very different from int* placeautobus[40].
I have also taken the liberty of including the variable names in the method declaration, this provides essential information to the reader, even though the compiler ignores it.
In the implementation of calculdesplaces(), you can access the argument array precisely the same way as you can access any 2D array:
int autobus::calculdesplaces(int typeautobus, int (*placeautobus)[40]) {
int placenumero;
for (int place = 0; place < 40; place++) {
if ( placeautobus[typeautobus][place] ==0) {
placenumero = place+1;
cout <<"Places : "<< placenumero <<endl;
}
}
return placenumero;
}
Now you can easily call your function by just passing the array:
int main() {
int TypeAutobus;
autobus *choixautobus = new autobus();
cout << "1 for smoking bus" << endl;
cout << "2 for non-smoking bus" << endl;
cin >> TypeAutobus;
choixautobus->calculdesplaces(TypeAutobus, choixautobus->placeautobus);
system("PAUSE");
return EXIT_SUCCESS;
}
Note:
The above only fixes the symptoms, not the disease. The actual problem is, that the design of the class itself is flawed. Data members should generally not be public, and methods should work on the data of the object on which they are called, instead of relying on getting parts of the object passed in via additional arguments. So, the class definition should look like this:
class autobus{
public :
autobus();
void affichageTicket();
int calculdesplaces(int typeautobus);
private:
int placeautobus[2][40];
};
The definition of calculdesplaces() doesn't change that much, it just does not shadow the already available array member with a function argument:
int autobus::calculdesplaces(int typeautobus) {
int placenumero;
for (int place = 0; place < 40; place++) {
if ( placeautobus[typeautobus][place] ==0) {
placenumero = place+1;
cout <<"Places : "<< placenumero <<endl;
}
}
return placenumero;
}
And you don't need to "grab into the object" in main(), the array is implicitly passed via the this pointer:
int main() {
int TypeAutobus;
autobus *choixautobus = new autobus();
cout << "1 for smoking bus" << endl;
cout << "2 for non-smoking bus" << endl;
cin >> TypeAutobus;
choixautobus->calculdesplaces(TypeAutobus);
system("PAUSE");
return EXIT_SUCCESS;
}
You haven't mentioned what the error it. But I think this it the issue:
What is the data type of second argument in calculdesplaces function declaration:
int calculdesplaces(int, int);
It is: int
What is the data type of placeautobus[2][40] in calculdesplaces function definition:
int autobus::calculdesplaces(int typeautobus, int *placeautobus[2][40]){ ... }
It is: int*
What is the data type of placeautobus[2][40] in calculdesplaces function call:
choixautobus->calculdesplaces(TypeAutobus, choixautobus->placeautobus[2][40]);
Looking at class autobus { ... }, it is: int
So there is mismatch between the datatype used in function declaration, definition and call. Try solving this.
The code should not be compiled.
The member function declaration of calculdesplaces
int calculdesplaces(int, int);
does not coinside with its definition
int autobus::calculdesplaces(int typeautobus, int *placeautobus[2][40]){
The type of the second parameter differs.
As for the error message then the function should be called as
choixautobus->calculdesplaces( TypeAutobus, choixautobus->placeautobus );
Take into account that the function has a bug. You pass to the function as the first argument either 1 or 2 and use these values as indices of the array while the valid indices are 0 and 1.
Also the function does not need to have the second parameter because it deals with the data member
int placeautobus[2] [40];
So I would define the class and member functions the following way
class autobus{
public :
int placeautobus[2] [40];
autobus();
void affichageTicket();
int calculdesplaces(int);
};
#include <iostream>
#include "autobus.h"
autobus::autobus() : placeautobus {}
{
}
void autobus::affichageTicket()
{
}
int autobus::calculdesplaces( int typeautobus )
{
int placenumero = 0;
for (int place = 0; place < 40; place++)
{
if ( placeautobus[typeautobus - 1][place] == 0 )
{
placenumero = place+1;
cout <<"Places : "<< placenumero <<endl;
break;
}
}
return placenumero;
}
Though I do not understand what you return from the function.:)
Also you could specify the initialization of the array inside the class definition
class autobus{
public :
int placeautobus[2] [40] = {};
//...
In this case the main can look as
int main()
{
int TypeAutobus;
autobus *choixautobus = new autobus();
cout << "1 for smoking bus" << endl;
cout << "2 for non-smoking bus" << endl;
cin >> TypeAutobus;
choixautobus->calculdesplaces( TypeAutobus );
system("PAUSE");
return EXIT_SUCCESS;
}
Related
i have these set and get methods declared in my main cpp file
void issuesofRelevance::setApproach(int Approach) {
approach = Approach;
}
int issuesofRelevance::getApproach() {
return approach;
}
void issuesofRelevance::setSignifiance(int Significance) {
significance = Significance;
}
int issuesofRelevance::getSignificance() {
return significance;
}
The following H file is attatched in which I call the setMethods in its constructor.
class issuesofRelevance
{
public:
std::vector<std::string> issueName;
int significance;
int approach;
std::vector<std::string> newList;
issuesofRelevance(std::vector<std::string> issueName, int significance, int approach){
issueName = issueName;
significance = significance;
approach = approach;
setApproach(15);
setSignifiance(15);
}
issuesofRelevance();
void setIssues();
std::string getIssues();
void setApproach(int x);
void setSignifiance(int);
int getApproach();
int getSignificance();
};
I call the get functions in main int() as such
cout << object.getApproach();
cout << object.getSignificance();
However, when i go to run the code in the console I get no output when it should return the values of 10 and 15. Im unsure as to why this is occuring
Thankyou.
my full main as requested
int main(int argc, char* argv[]) { //takes in n, number of electorates, and m, the number of campagian days
issuesofRelevance newIssues(newIssues.issueName, newIssues.significance, newIssues.approach);
return 0;
Party party;
Person person;
Electrorates electorate;
string numberofElectoratesAsString = argv[1]; //number of electorates taking as a argument
string DaysOfElectionAsString = argv[2]; //takes in argument 2
int numberofElectorates = std::stoi(numberofElectoratesAsString);
int DaysOfElection = std::stoi(DaysOfElectionAsString );
cout << "Number of electorates: " << electorate.assignID(electorate.numberofElectorates(numberofElectorates));
cout << "Stance: " << person.setinitalStance(numberofElectorates, DaysOfElection) << endl;
newIssues.setIssues();
cout<<newIssues.getApproach()<< " "<<newIssues.getSignificance();
return 0;
}
default constructor
issuesofRelevance::issuesofRelevance(){
}
I've written this program that's supposed to solve a wheel with numbers from 1 to 11 and I'm having trouble with figuring out what's causing this Linker error. I believe I have everything else working fine in the code body except for this Boolean function that uses an integer array, but the error that comes up says the following. I'm not sure what I've done wrong with the function. I've declared it using a prototype in the beginning of the code, I call the function using its proper name and calling the array correctly. Could someone please help me figure out what's wrong with the code?
undefined reference to 'matchingSums(int)' … relocation truncated to fit: R_X86_64_PC32 against undefined symbol
#include <fstream>
#include <iostream>
#include <iomanip>
#include <string>
#include <time.h>
using namespace std;
const int MAX_CIRCLES = 11;
const int CENTER_CIRCLE_INDEX = 10;
bool matchingSums(int);
void fillTheWheel(int []);
void displayWheelContents(int []);
void randomizeTheContents(int, int []);
int nbrOfItems, firstSum, nextSum;
int main(void)
{
srand(time(NULL));
int wheel[MAX_CIRCLES];
int numInt = 0;
fillTheWheel(wheel);
while (!matchingSums(*wheel))
{
numInt++;
randomizeTheContents(MAX_CIRCLES, wheel);
}
cout << "After " << numInt << " unsuccessful attempts, the following solution was found:" << endl;
displayWheelContents(wheel);
}
void fillTheWheel(int wheel[])
{
for (int fillTheWheelIndex = 0; fillTheWheelIndex < MAX_CIRCLES; fillTheWheelIndex++)
{
wheel[fillTheWheelIndex] = (fillTheWheelIndex + 1);
}
}
void displayWheelContents(int wheel[])
{
cout << "* Outside circles (clockwise from the top):" << endl << " " << endl;
for (int wheelIndex = 0; wheelIndex < MAX_CIRCLES; wheelIndex++)
{
// Print each value in a column width of 4 as shown in the example-program-execution.txt file
cout << setw(4) << wheel[wheelIndex] << " ";
}
cout << " " << endl << " " << endl << "*Center circle: " << wheel[CENTER_CIRCLE_INDEX] << endl;
}
void randomizeTheContents(int nbrOfItems, int table[])
{
for (int indexA = 0; indexA < nbrOfItems; indexA++)
{
int indexB = rand() % nbrOfItems;
int temp = table[indexA];
table[indexA] = table[indexB];
table[indexB] = temp;
}
}
bool matchingSums(int wheel[])
{
const int MAX_OUTER_CIRCLES = MAX_CIRCLES - 1;
const int OPPOSITE_SIDE_FACTOR = 5;
const int STARTING_INDEX = 0;
int firstSum;
int nextSum;
// Calculate the sum of the first pair of numbers
firstSum = wheel[STARTING_INDEX] + wheel[CENTER_CIRCLE_INDEX]
+ wheel[STARTING_INDEX + OPPOSITE_SIDE_FACTOR];
// Compare the first sum to each of the sums of the other pairs
for (int i = 1; i < MAX_OUTER_CIRCLES/2; i++)
{
nextSum = wheel[i] + wheel[CENTER_CIRCLE_INDEX] + wheel[i + OPPOSITE_SIDE_FACTOR];
if (firstSum != nextSum)
return false;
} // End for
return true;
} // End matchingSums
Initially the function is declared with a parameter of the type int like
bool matchingSums(int);
And called with an argument of the type int in main
while (!matchingSums(*wheel))
But in its definition it is declared with a parameter of the type int [] that is implicitly adjusted by the compiler to the type int * like
bool matchingSums(int wheel[])
So the compiler issues an error because it did not find the definition of the function declared like
bool matchingSums(int);
The argument of matchingsums is of int type but the definition of the matchingSums function accepts int wheel[], an integer type of unsized array.
You must have overlooked this, since the function fillTheWheel accepts the same type of argument but was declared and defined just fine.
Replace the prototype
bool matchingSums(int) to bool matchingSums(int []).
The code snippet is as follows. The error is in foo function for the cout line:
typedef struct Datatype {
int first;
int second;
} Datatype;
void foo(std::array<Datatype, 100>* integerarray){
cout << *integerarray[0].first << endl; //ERROR: has no member first
}
void main() {
std::array<Datatype, 100> newarray;
for(int i=0; i<100; i++)
newarray[i] = i;
}
foo(&newarray);
}
Because of operator precedence, *integerarray[0].first is translated as *(integerarray[0].first), which is not what you want. You need to use (*integerarray)[0].first.
cout << (*integerarray)[0].first << endl;
You can make your life simpler by passing a reference.
void foo(std::array<Datatype, 100>& integerarray){
cout << integerarray[0].first << endl;
}
Also, you don't need to use typedef struct DataType { ... } DataType; in C++. You can use just struct DataType { ... };
newarray[i] = i;
In this line you have missed adding value to structure variables.
Also you have passed array as a reference to function. Removing it and passing just the name of array will pass base address of array.
I am adding following code for your reference:
#include<iostream>
#include <array>
struct Datatype{
int first;
int second;
}
typedef Datatype varInts;
void display(std::array<varInts,20> &dummy)
{
int b =5;
for(int i=0; i<20; i++)
{
dummy[i].first =b++;
dummy[i].second = b+5; //Give any logic you wish.just adding different values;
b++;
}
}
int main()
{
std::array<varInts,20> data;
int a =1;
for(int i=0;i<20;i++)
{
data[i].first = a++;
data[i].second = a+5;
a++; //Just adding values for example
}
display(data);
return 0;
}
It runs without error.Hope it helps!!
Imagine I have a class and it has a private value for example this value name is a, then I set it's value to 10.
How I can access to this variable with its value (10) in another class?
(I do not want to use friend function and friend class)
a.h
#include <iostream>
using namespace std;
static int s=0;
/* run this program using the console pauser or add your own getch, system("pause") or input loop */
class a
{
private:
public:
void sets(int );
};
a.cpp
#include "a.h"
void a::sets(int y){
cin >> y;
s=y;
}
main.cpp
#include"a.h"
int main()
{
int i=0;
int q;
a a1;
a1.sets(q);
cout << s+1 << endl;
for (i=1; i<5; i++){
if (s == i) cout << "ok";
}
}
If you do not want to use friendship, add a public interface to this variable (setter and/or getter class members).
Either make the variable public or add a function to get the value that returns it, like int getA() const { return a; } .
Use a private member s in your class a instead of a global variable, and access it via public Getter function GetS
Example:
#include <iostream>
using namespace std;
class a
{
private:
int s;
public:
void SetS() { cin >> s; }
int GetS() const { return s; }
};
int main()
{
a a1;
a1.SetS();
int s1=a1.GetS();
cout << s1+1 << endl;
for (int i=1; i<5; i++){
if (s1 == i) cout << "ok";
}
}
I have a class for performing various array operations. I like to use my insert method in my populate method.
Can someone guide me on that? Here is the code:
#include <iostream>
#include <cstdlib>
using namespace std;
const int MAX=5;
class array
{
private:
int arr[MAX];
public:
void insert(int pos, int num);
void populate(int[]);
void del(int pos);
void reverse();
void display();
void search(int num);
};
void array::populate(int a[])
{
for (int i=0;i<MAX;i++)
{
arr[i]=a[i];
}
}
void array::insert(int pos, int num)
{
for (int i=MAX-1;i>=pos;i--)
{
arr[i] = arr[i-1];
arr[i]=num;
}
}
void array::del(int pos)
{
for (int i=pos;i<MAX;i++)
{
arr[pos]=arr[pos + 1];
}
}
void array::display()
{
for (int i=0;i<MAX;i++)
cout<<arr[i];
}
void array::search(int num)
{
for (int i=0;i<MAX;i++)
{
if (arr[i]==num)
{
cout<<"\n"<<num<<" found at index "<<i;
break;
}
if (i==MAX)
{
cout<<num <<" does not exist!";
}
}
}
int main()
{
array a;
for (int j=0;j<MAX;j++)
{
a.insert(j,j);
}
a.populate(a);
a.insert(2,7);
a.display();
a.search(44);
system("pause");
}
I like to use my insert method in my
populate method. Can someone guide me
on that?
That would mean that instead of the straightforward and efficient "copy from one array to another" approach, you'd call insert for each value of the input with the correct index in place of the assignment.
To call a method on the current instance, from inside a method:
insert(x, y);
//or
this->insert(x, y);
Your code also contains an error, in that you pass a wrong type to populate in main. It expect int* (a real array), not an array object.
Please elaborate your question. If you just need a good container have a look at the STL (Standard Template Library) std::vector. It's part of the C++ standard and comes with your compiler.
If you want to learn how to write a custom class, please try to be more precise in your question.
Also consider the wealth of beginner tutorials available on the net, for example:
http://www.learncpp.com/
Here is a little example on how to write a custom class with one member function calling the other and accessing a private data member (note that inside a member function you can refer to any other member directly):
#include <iostream>
class Example
{
private:
int some_private_stuff;
public:
Example();
void function_a();
void function_b();
};
Example::Example(){
some_private_stuff = 1;
}
void Example::function_a(){
std::cout << "this is function a" << std::endl;
some_private_stuff = 2;
std::cout << "changed private_stuff to " << some_private_stuff << std::endl;
}
void Example::function_b(){
std::cout << "this is function b" << std::endl;
function_a();
}
int main() {
Example e;
e.function_b();
return 0;
}