Why cant i overload the * operator? [duplicate] - c++

This question already has answers here:
What are the basic rules and idioms for operator overloading?
(8 answers)
Closed 6 years ago.
#include <iostream>
#include <string>
using namespace std;
class sequence{
public:
sequence();
sequence(int x);
sequence& operator*=(const &left, const &right);
~sequence();
friend istream& operator >>(istream&, sequence&);
friend ostream& operator <<(ostream&, sequence&);
void set_num_samples(); //Set no. of samples
float* value; //pointer to float variable
void allocate_memory(); //Allocates memory
void set_values_array(); //Sets the values of an array
void check_array_input(float l); //Checks the values of the array
void reset_input(float j); //Resets the array
void de_allocate(); //deallocates memory
int get_num_samples();
void set_full_array(int x);
void calculate_full(float array1[], float array2[]);
void combine_seq_coef(sequence& inputvoltageA); //Combines the passed in sequence and coefficient
void combine_seq(sequence& objectcombine, int sample); // combine the sequences
private:
int num_samples; //number of samples in the object sequence
};
class FIR{
public:
FIR();
~FIR();
private:
int num_coefficients; //Number of coefficients in an FIR (filter impulse response)
};
//Constructor for each object
void sequence::set_num_samples() { //Set_num_sample definition
cout << "Please enter the number of values in your sequence: \n";
cin >> num_samples;
if(num_samples < 0){
cout << "Value entered must be greater than 0 "<< endl;
cout << "Please enter the value again: " << endl;
cin >> num_samples;
}
}; //ok (stream op)
void sequence::allocate_memory() {
value = new float[num_samples]; //Allocated memory for Array.
}; //ok
void sequence::set_values_array(){ //Set values for array
int k;
for(k=0; k<num_samples; k++){
cout << "Please enter a positive value for element : " << (k+1) << endl;
cin >> value[k];
while(value[k] < 0){
cout << "Enter positive value " << endl;
cin >> value[k];
}
}
cout << "Values have been assigned successfully! " << endl;
}; //ok
//Constructor functions
void sequence::check_array_input(float l) { //Checks array values.
cout << endl << "If you would like to check input values, enter 'y' otherwise, enter 'n' to continue..." << endl;
char check_value;
cin >> check_value;
if (check_value == 'y') {
int i;
for (i = 0; i < l; i++) {
cout << "Value no. " << (i + 1) << " is:" << endl;
cout << value[i] << endl;
}
}
}
void sequence::reset_input(float j) { //Reset voltage value and set to 0;
cout << endl << "If you would like to reset all input values, enter 'y' otherwise, enter 'n' to continue..."
<< endl;
char check_value2;
cin >> check_value2;
if (check_value2 == 'y') {
int i;
for (i = 0; i < j; i++) {
cout << "Value no." << (i + 1) << ": " << value[i];
value[i] = 0;
cout << " is set to 0!" << endl;
}
}
}
void sequence::de_allocate(){
delete[] value; //De-allocate memory
num_samples = 0;
cout << "De-allocation of input array successful, num of samples reset to 0! " << endl;
}
int sequence::get_num_samples(){
return num_samples;
}
/* void sequence::calculate_full(float array1[], float array2[]){
int loop;
for(loop=0; loop<num_samples; loop++){
cout << "CoefficientA value no: " << (loop+1) << ": " << array1[loop].value[loop] << endl;
cout << "InputvoltageA value no." << (loop+1) << ": " << array2[loop].value[loop] << endl;
value[loop] = (array1[loop].value[loop])*(array2[loop].value[loop]);
cout << "Combined value no. " << (i+1) << ": " << value[loop] << endl;
cout << "The combined value gives" << full[loop] << endl;
}
}; */
void sequence::set_full_array(int x){
num_samples = x;
}
void sequence::combine_seq(sequence& object_combine, int sample_num){
int loop;
for(loop=0; loop<sample_num; loop++){
}
};
sequence& sequence::operator*=(const &left, const &right){
int y = left.get_num_samples();
int x;
for (x=0; )
sequence = left.value * right.value
return sequence;
}
sequence::sequence(){ //SEQUENCE CONSTRUCTOR
set_num_samples();
allocate_memory();
set_values_array();
check_array_input(num_samples);
reset_input(num_samples);
de_allocate();
cout << endl << "Constructor complete!" << endl;
};
sequence::sequence(int a){ //sequence constructor 2
set_full_array(a);
allocate_memory();
}
/* sequence::sequence(int a){
set_full_samples();
allocate_memory();
int i;
for(i=0; i<num_samples; i++){
cout << "CoefficientA value no: " << (i+1) << ": " << coefficientA().value[i] << endl;
cout << "InputvoltageA value no." << (i+1) << ": " << inputvoltageA.value[i] << endl;
cout << "Combined value no. " << (i+1) << ": " << value[i] << endl;
}
}
*/
sequence::~sequence(){ //Destructor
cout << "Destructor is called" << endl;
}; //destructor
int main(){
// Create object, constructor called
// Constructor calls, set_num_sample, allocate_memory, set_values_array
// Enters values for voltage Inputs to the sequence into an array
// Checks values of the array
// Asks user if they want to reset values and set num samples = 0.
do {
cout << "Press the Enter key to continue:" << endl;
} while (cin.get() != '\n');
cout << "Input voltage sequence created!" << endl;
sequence inputvoltageA;
cout << endl << "CoefficientA sequence created!" << endl;
sequence coefficientA;
//Combines sequence and coefficients
cout << "If you would like to combine the coefficients with the input sequence A enter 'y', otherwise enter 'n'" << endl;
char prompt4;
cin >> prompt4;
if(prompt4 == 'y'){
int x = coefficientA.get_num_samples();
sequence full(x);
full = coefficientA*inputvoltageA;
}
/* Ask the user if they want to create new object
cout << "If you would like to create a new input voltage sequence enter 'y', otherwise enter 'n'" << endl;
char prompt3;
cin >> prompt3;
if(prompt3 == 'y'){
sequence inputvoltageB;
}
cout << "CoefficientA sequence created!" << endl;
sequence coefficientB;
*/
/*
cout << "If you would like to combine this sequence with the sequence before enter 'y', otherwise enter 'n'" << endl;
char prompt5;
cin >> prompt5;
if(prompt5 == 'y'){
combine_seq(inputvoltageA, num_samples);
} */
return 0;
}
Why cant i overload the * operator?
The compiler gives me the error c++ must have a type specifier.
My type specifier is a reference to a sequence object...
I think ive defined the overload operator * function correctly in the class and outside of it.

You're overloading operator*= not operator*. operator*= is a binary operator - you either need to:
define it as a friend binary function inside the class body;
friend auto& operator*=(sequence& l, sequence& r) { /* ... */ }
define it as a non-friend unary function inside the class body (where the left-hand side is implicitly *this);
auto& operator*=(sequence& r) { /* ... */ }
define it as a free binary function outside the class body.
auto& operator*=(sequence& l, sequence& r) { /* ... */ }
Also, your function parameters need types. const& left does not have a type - you probably want const sequence& left.

Related

How can you change signs of the elements of Array in C++

I just want to ask a question.
I am coding a system of linear equations in two variables using the 2-dimensional array. on the second equation, it is always multiplied with - so that it is easier to solve the x or y in equation 1.
how can you change the sign of the numbers in equation 2 if the ax+by= c is not the same?
I only know how to negate all the numbers in the second equation with the use of negative absolute value but I am facing difficulty if the user inputs on negative and positive numbers in equation 2.(-2x + 3y = -4).
Here is my code (it is not done since I am confused on how to change signs of an array independently because of the user input. I am just a beginner)
/*
Linear equation using elimination method
*/
#include <iostream>
#include <iomanip>
#include <cmath>
using namespace std;
const int row = 2;
const int col = 3;
int list[row][col];
int list1[row][col];
int list2[row][col];
int rsize, y, x;
char operation;
int ir, ic;
int *ptr;
//function declaration
void equation1(int list[][col], int rsize);
//to display the value in 2D array plus linear equation
void Elimination(int list1[][col], int rsize);
//input the 2 values to elimate in eqn1 and eqn2
//then display the new equations that is already multiplied to the 2values
void final1(int list1[][col], int rsize,int Y);
//diplay the value of computed Y and the equation need to substitute the value of Y
//process and computes the value of X
//and finally, display the solution set of (x,y)
void final2(int list1[][col], int rsize,int X);
//diplay the value of computed X and the equation need to substitute the value of X
//process and computes the value of Y
//and finally, display the solution set of (x,y)
int deterY(int list2[3]); //computes the value of Y and returns the value of Y
int deterX(int list2[3]); //computes the value of X and returns the value of X
char choice(); //display the menu and returns the value of choice
int main() {
char opt, ulit, operation;
int equation;
opt = choice();
int solve_for_x, solve_for_y;
switch(opt) {
case '1': //two dimensional
do {
system("cls");
cout << "SYSTEMS OF LINEAR EQUATIONS:\n"
<< "Solving by addition or elimination\n";
//ADD CODE HERE
cout << "This program uses Addition or Elimination Method.\n"
<< "We begin by setting up and evaluating the three variables x, y and the constant.\n"
<< "For example,\n 5x + y = -14 \nshould be entered as 5 1 -14";
cout << "\n\nPress any key to continue....";
cin >> opt;
cin.ignore();
cin.get();
system("cls");
cout << "Again, 5x + y = -14 should be entered as 5 1 -14\n";
//ADD CODE HERE
equation1(list, row);
cin.ignore();
cout<<"\n\nPress any key to continue...." <<endl;
cin.get();
system("cls");
Elimination(list1, row);
cout << "\n\n\n";
cout << "What variable do you want to change: \n";
cout << "x or y\n";
cin >> operation;
switch(operation){
case 'x':
solve_for_x = deterX(list2[3]);
cout << solve_for_x <<endl;
break;
case 'y':
solve_for_y = deterY(list2[3]);
cout << solve_for_y << endl;
break;
}
//Call function Elimination here
//ADD CODE HERE
} while (toupper(ulit) == 'Y');
break;
case '2':
//ADD CODE HERE
break;
} //end switch
system("pause");
return 0;
} //end main
///////////////////////////////////////////////////////////
char choice() {
cout << "<<<<<<<MENU>>>>>>>" << endl;
cout <<"[1] Systems of Linear Equation"<<endl;
cout <<"[2] Quit" << endl;
cout <<"Enter your choice:" << endl;
char opt;
cin >> opt;
return opt;
}
///////////////////////////////////////////////////////////////
void equation1(int ist[][col], int rsize) {
cout << "Enter Equation 1:";
for(ir = 0; ir < row; ir++) {
for(ic = 0; ic < col; ic++) {
if(ir == 0 && ic >= 0) {
cin >> list[ir][ic];
}
if(ir == 1 && ic >= 0) {
cout << "Enter Equation 2:";
cin >> list[ir][ic];
}
}
}
} //end equation1
///////////////////////////////////////////////////////////
void Elimination(int list1[][col], int rsize) {
cout << "you have entered (using 2-dimensional array)" << endl;
for(ir = 0; ir < row; ir++) {
for(ic = 0; ic < col; ic++) {
cout < <setw(7) << list[ir][ic];
}
cout << endl;
}
cout << endl;
cout << "SOLVING SIMPLE EQUATIONS" << endl;
cout << setw(7) << list[0][0] << "x" << " + " <<list[0][1] << "y" << " = " << list[0][2] << endl;
cout << setw(7) << list[1][0] << "x" << " + " <<list[1][1] << "y" << " = " << list[1][2] << endl;
cout << "\n\n\n\n";
cout <<"_____________________________________________________ "<< endl;
cout << "Please enter the value to eliminate the variable" << endl;
cout << "for example... if you have:" <<endl;
cout << "2x + 3y = 10" << endl;
cout << "4x + 5y = 15" << endl;
cout << "if you want to eliminate the x.. you need to input -2" << endl;
cout << "(for 2x to become -4x in eqn.1) and 1 (to remain the value in eqn.2" << endl;
cout << "if you want to eliminate y.. you need to input -/+5 in eqn1 and +-3 in eqn.2" << endl;
cout << "enter the value for equation 1: 1 " << endl;
cout << "enter value for equation 2: -1 " << endl;
cout << "\n\n\n";
cout << "ELIMINATING EQUATIONS" << endl;
cout << setw(7) << list[0][0] <<"x" << " + " <<list[0][1] <<"y" << " = " << list[0][2] << endl;
cout << setw(7) << -abs(list[1][0])<<"x" << " + " << -abs(list[1][1]) <<"y" << " = " << -abs(list[1][2]) << endl;
cout <<"===================================================== "<< endl;
}
////////////////////////////////////////////////////
int deterY(int list2[3]){}
///////////////////////////////////////////////
int deterX(int list2[3]) {}
///////////////////////////////////////////////////////
void final1(int list1[][col], int rsize,int Y) {}
////////////////////////////////////////////////////////////////////////////
void final2(int list1[][col], int rsize,int X) {}

Searching through char array

In CPP file #1, I'm trying to loop through the array to see if any of the inputed names match Mordor or the_Vale (from CPP file #2 towards the bottom), however my loop is not working and I only know how to loop through a string array, not a char
#Header File#
#ifndef KINGDOM_H
#define KINGDOM_H
namespace westeros
{
class Kingdom
{
public: //Makes this class public to the rest of the code
char m_name[32];
int m_population;
int count = 0;
};
void display(Kingdom&);
void display(Kingdom* k, int x);
void display(Kingdom* k, int x, int z);
void display(Kingdom* k, int x, char foo[]);
}
#endif
#CPP FIle #1#
#include <iostream>
#include "kingdom.h"
void display(Kingdom* k, int x, char foo[])
{
int a = 0;
int found = 0;
cout << "Searching for kingdom " << foo << " in Westeros" << endl;
for (a; a < x; a++)
{
if (k[a].m_name == foo)
//(strcmp(k[a].m_name) == 0)//Not working
{
cout << k[a].m_name << ", population " << k[a].m_population << endl;
found = 1;
}
}
if (found == 0)
{
cout << foo << " is not part of Westeros." << endl;
}
}
}
## CPP File (main) #2##
#include <iostream>
#include "kingdom.h"
using namespace std;
using namespace westeros;
int main(void)
{
int count = 0; // the number of kingdoms in the array
// TODO: declare the kingdoms pointer here (don't forget to initialize it)
Kingdom* pKingdoms = nullptr;
cout << "==========" << endl
<< "Input data" << endl
<< "==========" << endl
<< "Enter the number of kingdoms: ";
cin >> count;
cin.ignore();
pKingdoms = new Kingdom[count];
for (int i = 0; i < count; ++i)
{
// TODO: add code to accept user input for the kingdoms array
int x = 0;
x++;
cout << "Enter the name for kingdom #" << x + i << ": ";
cin >> pKingdoms[i].m_name;
cout << "Enter the number people living in " << pKingdoms[i].m_name << ": ";
cin >> pKingdoms[i].m_population;
}
cout << "==========" << endl << endl;
// testing that "display(...)" works
cout << "------------------------------" << endl
<< "The first kingdom of Westeros" << endl
<< "------------------------------" << endl;
display(pKingdoms[0]);
cout << "------------------------------" << endl << endl;
// This is where I am having the problem
display(pKingdoms, count, "Mordor");
cout << endl;
display(pKingdoms, count, "The_Vale");
cout << endl;
cout << endl;
delete[] pKingdoms;
pKingdoms = nullptr;
return 0;
}
if (k[a].m_name == foo)
This is not how you compare two C-Style strings. This only compares the pointers, which should result in false almost certainly. You could use strcmp (#include <string.h>):
if (!strcmp(k[a].m_name, foo))
A better way, though, since you're programming in C++, use std::string:
std::string m_name;
and the comparison would have worked flawlessly.

C++ inventory item removal

Increase the inventory to be 10 items. DONE!!!
Create a for loop that asks the user to input the initial items in the inventory.DONE!!!
After the for loop create a minor story where the healer changes two items (i.e. items 4 and 8).What I want is to SWAP an item for another item ie would you like to trade your {[item] for [item2] y or n
Sort the inventory in alphabetical order. You can use your own sort if you want, but here is a bubble sort algorithm:
// A simple inventory program using a struct to store data
// in an array.
#include <cstdlib>
#include <iostream>
#include <iomanip>
#include <fstream>
#include <string>
#include <sstream>
using namespace std;
// define a data structure
struct InventoryRecord
{
string name; // inventory item name
int qty; // how many are in stock
double value; // the value
};
// const for the max size of the record array
const int MAX_SIZE = 9;
// function prototypes
void addData(InventoryRecord list[], int& size);
void dispData(const InventoryRecord list[], int size);
void remData( const InventoryRecord list[], int size);
void saveFile(const InventoryRecord list[], int size);
void openFile(InventoryRecord list[], int& size);
char getMenuResponse();
int main(int argc, char *argv[])
{
InventoryRecord recList[MAX_SIZE];
int numOfRecs = 0;
bool run = true;
do
{
cout << "Hero's Inventory - " << numOfRecs << " items in your bag" << endl;
switch ( getMenuResponse() )
{
case 'A': addData(recList, numOfRecs); break;
case 'D': dispData(recList, numOfRecs); break;
case 'R': remData(recList, numOfRecs); break;
case 'O': openFile(recList, numOfRecs); break;
case 'S': saveFile(recList, numOfRecs); break;
case 'Q': run = false; break;
default : cout << "That is NOT a valid choice" << endl;
}
} while (run);
cout << endl << "Program Terminated" << endl;
// system("PAUSE"); // Program exits immediatly upon "Quit" if commented out
return EXIT_SUCCESS;
}
// Task: Allow data entry of one inventory item
// Accepts: References to the inventory array and its size
// Returns: Nothing
// Modifies: The array and size 'actual parameter'
// NOTE: Could be modified to allow entry of more than one item
void addData(InventoryRecord list[], int& size)
{
InventoryRecord tmp; // declare a temp item that we will load before putting in the array
char response;
char str[256]; // needed for cin.getline; we are going to use a char array
if (size < MAX_SIZE) {
system("cls");
cout << "Please enter 10 items helpful to your quest! " << endl;
cout << "Enter item: " << endl << endl;
cout << "Name: ";
// Get up to 256 characters from the keyboard including white space.
// Stop reading if encounter the \n first. If there's any chance of
// more than 256 characters you will have to clean up cin with
// cin.ignore before the next input.
cin.getline(str, 256, '\n'); // for char arrays; different from the other getline
tmp.name = str;
cout << "Quantity: ";
cin >> tmp.qty;
cout << "Value: ";
cin >> tmp.value;
cout << endl;
// see if this record should be added to the array
cout << "Add to inventory? (y/n) ";
cin >> response;
if (toupper(response) == 'Y')
list[size++] = tmp;
} else {
cout << "Inventory is full; cannot enter more units." << endl;
system("pause");
}
system("cls");
}
void dispData(const InventoryRecord list[], int size)
{
system("cls");
double cost = 0;
if(size < 1) {
cout << "Nothing to display" << endl;
} else {
cout << "All Items in your Bag" << endl << endl;
cout << fixed << setprecision(2);
cout << "Item Name Qty Value" << endl;
cout << "~~~~~~~~~~~~~~~~~~" << endl;
cout << left;
for (int i = 0; i < size; i++) {
cout << setw(21) << list[i].name << right
<< setw(4) << list[i].qty
<< setw(10) << list[i].value << left << endl;
cost = cost + list[i].value * list[i].qty;
}
cout << "~~~~~~~~~~~~~~~~~~~" << endl;
cout << right << setw(3) << size;
cout << " items listed";
cout << right << setw(19) << cost << endl << endl;
}
system("PAUSE");
system("cls");
}
void remData(const InventoryRecord list[], int size) {
system("cls");
cout <<"Enter Item you wish to remove from your inventory: " << endl;// This is being displayed so user can see items in the inventory
double cost = 0;
if(size < 1) {
cout << "Nothing to display" << endl;
} else {
cout << "All Items in your Bag" << endl << endl;
cout << fixed << setprecision(2);
cout << "Item Name Qty Value" << endl;// It is not displaying right the alignment is off
cout << "~~~~~~~~~~~~~~~~~~" << endl;
cout <<"Item Name: ";/* from here I do not know what to do! What I want is have use type the item name they want removed
also display an error if they enter an item wrong*/
cout << left;
for (int i = 0; i < size; i++) {
cout << setw(21) << list[i].name << right
<< setw(4) << list[i].qty
<< setw(10) << list[i].value << left << endl;
cost = cost + list[i].value * list[i].qty;
}
cout << "~~~~~~~~~~~~~~~~~~~" << endl;
cout << right << setw(3) << size;
cout << " items listed";
cout << right << setw(19) << cost << endl << endl;
}}
// Save records to disc
void saveFile(const InventoryRecord list[], int size) {
ofstream outfi("Inventory.txt");
// make sure the file stream is open before doing IO
if (!outfi.fail()) {
system("cls");
cout << "Saving inventory to the disc ";
for(int i = 0; i < size; i++) {
outfi << list[i].name << ';'
<< list[i].qty << ';'
<< list[i].value;
// Start a new line after all but the last record
// Simplifies reading the file as EOF is at end of last line
if (i < size-1) outfi << endl;
}
cout << endl << size << " records writen to the disc." << endl;
outfi.close();
system("PAUSE");
system("cls");
}
else {
cout << "ERROR: problem with file" << endl;
system("PAUSE");
system("cls");
}
}
// Open file and load array
void openFile(InventoryRecord list[], int& size)
{
ifstream infi("Inventory.txt");
string str;
stringstream strstrm;
// make sure the file stream is open before doing IO
if (!infi.fail()) {
system("cls");
cout << "Reading inventory from the disc ";
size = 0; // overwrite any existing records
while(!infi.eof() && size < MAX_SIZE) {
// get and store the name
getline(infi, str, ';');
list[size].name = str;
// get, convert and store the quantity
getline(infi, str, ';');
strstrm.str(""); strstrm.clear(); // empty and clear the stringstream
strstrm << str;
strstrm >> list[size].qty;
// get, convert and store the cost
getline(infi, str);
strstrm.str(""); strstrm.clear(); // empty and clear the stringstream
strstrm << str;
strstrm >> list[size++].value;
}
cout << endl << size << " records read from the disc." << endl;
system("PAUSE");
system("cls");
}
else { // something went wrong with opening the file
cout << "ERROR: problem with file" << endl;
system("PAUSE");
system("cls");
}
}
char getMenuResponse()
// Task: Put the menu on screen and get a response
// Accepts: Nothing
// Returns: The users response
// Modifies: Nothing
// NOTE: Characters are far more intuitive at the command
// line than numbers; avoid using numbers.
{
char response;
cout << endl << "Make your selection" << endl
<< "(A)dd Items, (D)isplay Items, (R)emove items, (O)pen File, (S)ave File, (Q)uit" << endl
<< "> ";
cin >> response;
cin.ignore(256, '\n');
// clean-up up to 256 chars including the delimiter specified (\n, the endl)
// OR stop when the \n is encountered after removing it.
return toupper(response);
}
To remove an element from your inventory, you just need to move all elements after the removed element one position forward. Once that is done, you also need to reduce the lengthy by one. For example, to remove the elements at the position index from an array array with currently length elements you could use
if (index < length) {
std::copy(array + index + 1, array + length, array + index);
++length;
}
There are essentially two ways to remove the element, the easiest is swap the element which you want to delete with the last one and resize the list:
void deleteElem(Data[] list, int & listLength, int ix) {
if (ix < listLength - 1) {
list[ix] = list[listLength - 1];
}
--listLength;
}
The second solution is memmove everthing after the to deleting element one to the left:
void deleteElem(Data[] list, int & listLength, int ix) {
memmove(list[ix], list[ix + 1], (listLength - ix - 1) * sizeof(Data));
--listLength;
}
EDIT: There was an error in the length for memmove, always the same. You should read the documentation.

Overloading operators..getting a logical error

I am having some trouble When I run my current program. I can add any number of transactions within this account balance, but when I go past the first array value and enter information, it displays a memory location.. Whats my problem in my code then here.
for(int i = 0; i < ACCTS; ++i)
{
do
{
debitCredit = accounts[x].operator+=(accounts[x]);
cout << "Account Balance is:$" << debitCredit << endl;
cout << "Enter " << QUIT << " to stop transactions." << endl;
cin >> selection;
}while(selection != QUIT);
++x;
}
The source code for this is here:
//Alex Weir
// Case 2 Chapter 9
#include <iostream>
#include <iomanip>
using namespace std;
class BankAccount
{
friend ostream& operator<<(ostream&, const BankAccount&);
friend istream& operator>>(istream&, BankAccount&);
private:
int accountNum;
int increaseAccountNum;
double accountBal;
double annualIntRate;
double debitCredit;
public:
BankAccount();
BankAccount(int,int,double,double,double);
int operator==(const BankAccount&);
void operator<(const BankAccount&);
void operator>(const BankAccount&);
double operator+=(BankAccount);
int operator+(BankAccount);
void displayAccounts();
};
double BankAccount::operator+=(BankAccount account)
{
cout << "How much money would you like to deposit or withdraw?" << endl <<
" Enter a negative amount to withdraw." << endl;
cin >> debitCredit;
debitCredit = debitCredit + account.accountBal;
return debitCredit;
}
int BankAccount::operator+(BankAccount account)
{
int increment;
int accountNum = increment + account.accountNum;
return accountNum;
}
void BankAccount::operator>(const BankAccount& accounts)
{
if(accountBal > accounts.accountBal)
{
cout << "Account Balance is greater than another account." << endl;
}
else
{
cout << "Account Balance is less than another account." << endl;
}
}
void BankAccount::operator<(const BankAccount& accounts)
{
if(accountBal < accounts.accountBal)
{
cout << "Account Balance is less than another account." << endl;
}
else
{
cout << "Account Balance is greater than another account." << endl;
}
}
BankAccount::operator==(const BankAccount& acctNumb)
{
int isTrue = 0;
if(accountNum == acctNumb.accountNum)
isTrue = 1;
return isTrue;
}
ostream& operator << (ostream& out, const BankAccount& Accounts)
{
cout << endl;
out << "Account #" << Accounts.accountNum << endl;
out << "Account Balance:$" << Accounts.accountBal << endl;
out << "Account interest rate: " << Accounts.annualIntRate << endl;
cout << endl;
return out;
}
istream& operator >> (istream& in, BankAccount& Accounts)
{
cout << "Enter Account # " << endl;
in >> Accounts.accountNum;
cout << "Enter Account Balance: $";
in >> Accounts.accountBal;
cout << endl << "Enter Account Interest Rate: " << endl;
in >> Accounts.annualIntRate;
cout << endl;
return in;
}
BankAccount::BankAccount()
{
accountNum = 0;
accountBal = 0;
annualIntRate = 0;
increaseAccountNum = 0;
debitCredit = 0;
}
BankAccount::BankAccount(int acctNum, int increment, double acctBal, double intRate, double debCred)
{
accountNum = acctNum;
accountBal = acctBal;
annualIntRate = intRate;
increaseAccountNum = increment;
debitCredit = debCred;
}
void BankAccount::displayAccounts()
{
cout << "Account # " << accountNum << endl;
cout << "Account balance:$" << accountBal << endl;
cout << "Account Interest Rate: " << annualIntRate << endl;
cout << endl;
}
int main()
{
const int ACCTS = 5;
const int QUIT = 0;
int x, selection;
double debitCredit = 0.0;
BankAccount accounts[ACCTS];
cout << "Enter Bank account information for: " << ACCTS << " accounts." << endl;
for(x = 0; x < ACCTS; ++x)
{
accounts[x].displayAccounts();
}
for(int i = 0; i < ACCTS; ++i)
{
do
{
debitCredit = accounts[x].operator+=(accounts[x]);
cout << "Account Balance is:$" << debitCredit << endl;
cout << "Enter " << QUIT << " to stop transactions." << endl;
cin >> selection;
}while(selection != QUIT);
++x;
}
for(x = 0; x < ACCTS; ++x)
{
accounts[x].displayAccounts();
}
/*for(x = 0; x < ACCTS; ++x)
{
cout << "Entry #" << (x + 1) << endl;
cin >> accounts[x];
cout << accounts[x];
}
double transactions;
for(x = 0; x < ACCTS; ++x)
{
}*/
Okay now that I have gotten rid of x I continue to have my variable as "i" now, I go through the 5 array elements, but I want to start with array 0 then go through the loop as many times as I want to (still playing with the balance at array element 0) after I hit "stop" or 0 when given the opportunity I want to move onto the 1st array element and go through it, adding and sub tracting for as much as I feel nessacary and repeating this process until I am fine with it. re setting the array's element variable to "i" does not do this and carries over from the last array element used.
system("pause");
return 0;
}
There are several things that might be wrong here:
debitCredit = accounts[x].operator+=(accounts[x]);
Why don't you use i instead of x? Is the value of x even initialized (the code doesn't show)?
Why do you add accounts[x] to itself? In effect you are doubling its value.
Is the accounts array big enough? How is it initialized?
Update
After looking at the extra code you posted: lose the x and use i instead. You are overstepping the bounds of the accounts array.

C++ 2d Array Class Function Call Help

I hope this question takes a simple fix, and I am just missing something very small.
I am in my second semester of C++ in college, and we are just getting into OOP. This is my first OOP program, and it is causing me a little problem. Here are the errors I am getting:
Member function must be called or its address taken in function displayGrid(int,Cell ( *)[20])
Member function must be called or its address taken in function Turn(int,int,Cell ( *)[20])
Member function must be called or its address taken in function Turn(int,int,Cell ( *)[20])
Warning: Parameter 'grid' is never used in function displayGrid(int,Cell ( *)[20])
Here is all of my code. I am aware It is much more code than necessary, sorry if it makes it more difficult. I was worried that I might accidentally delete something.
const int MAX=20;
//Struct Cell holds player and their symbol.
class Cell
{
private:
int Player;
char Symbol;
public:
Cell(void);
void setPlayer(int);
void setSymbol(char);
int getPlayer(void);
char getSymbol(void);
};
Cell::Cell(void)
{
Symbol ='-';
}
void Cell::setPlayer(int player_num)
{
Player = player_num;
}
void Cell::setSymbol(char rps)
{
Symbol = rps;
}
int Cell::getPlayer(void)
{
return Player;
}
char Cell::getSymbol(void)
{
return Symbol;
}
void Turn(int, int, Cell[MAX][MAX]);
void displayGrid(int, Cell[MAX][MAX]);
void main(void)
{
int size;
cout << "How big would you like the grid to be: ";
cin >> size;
//Checks to see valid grid size
while(size>MAX || size<3)
{
cout << "Grid size must between 20 and 3." << endl;
cout << "Please re-enter the grid size: ";
cin >> size;
}
int cnt=1;
int full;
Cell grid[MAX][MAX];
//I use full to detect when the game is over by squaring size.
full = size*size;
cout << "Starting a new game." << endl;
//Exits loop when cnt reaches full.
while(cnt<full+1)
{
displayGrid(size, grid); //calls function to display grid
if(cnt%2==0) //if cnt is even then it's 2nd players turn
cout << "Player 2's turn." << endl;
else
cout << "Player 1's turn" << endl;
Turn(size, cnt, grid); //calls Turn do each players turn
cnt++;
}
cout << endl;
cout << "Board is full... Game Over" << endl;
}
void displayGrid(int size, Cell grid[MAX][MAX])
{
cout << endl;
cout << " ";
for(int x=1; x<size+1; x++) // prints first row
cout << setw(3) << x; // of numbers.
cout << endl;
//Nested-For prints the grid.
for(int i=1; i<size+1; i++)
{
cout << setw(2) << i;
for(int c=1; c<size+1; c++)
{
cout << setw(3) << grid[i][c].getSymbol;
}
cout << endl;
}
cout << endl;
}
void Turn(int size, int cnt, Cell grid[MAX][MAX])
{
char temp;
char choice;
int row=0;
int column=0;
cout << "Enter the Row: ";
cin >> row;
cout << "Enter the Column: ";
cin >> column;
//puts what is in the current cell in "temp"
temp = grid[row][column].getSymbol;
//Checks to see if temp is occupied or not
while(temp!='-')
{
cout << "Cell space is Occupied..." << endl;
cout << "Enter the Row: ";
cin >> row;
cout << "Enter the Column: ";
cin >> column;
temp = grid[row][column].getSymbol; //exits loop when finally correct
}
if(cnt%2==0) //if cnt is even then its player 2's turn
{
cout << "Enter your Symbol R, P, or S (Capitals): ";
cin >> choice;
grid[row][column].setPlayer(1);
in >> choice;
}
//officially sets choice to grid cell
grid[row][column].setSymbol(choice);
}
else //if cnt is odd then its player 1's turn
{
cout << "Enter your Symbol r, p, or s (Lower-Case): ";
cin >> choice;
grid[row][column].setPlayer(2);
//checks for valid input by user1
while(choice!= 'r' && choice!='p' && choice!='s')
{
cout << "Invalid Symbol... Please Re-Enter: ";
cin >> choice;
}
//officially sets choice to grid cell.
grid[row][column].setSymbol(choice);
}
cout << endl;
}
Thanks alot for your help!
The following line:
cout << setw(3) << grid[i][c].getSymbol;
Doesn't call the function. Write this instead:
cout << setw(3) << grid[i][c].getSymbol();
Likewise for the other error messages.
The warning is generated because the erroneous line is the only time displayGrid uses the grid parameter.
You forgot the function parens:
cout << setw(3) << grid[i][c].getSymbol;
should be:
cout << setw(3) << grid[i][c].getSymbol();