#include<iostream>
using namespace std;
class distance //class
{
private:
int feet;
float inches;
public:
distance() :feet(0), inches(0.0) //constructor
{}
distance(int ft, float in) :feet(ft), inches(in) //constructor
{}
void getdist() //get values
{
cout << "Enter feet :";
cin >> feet;
cout << "Enter inches :";
cin >> inches;
}
void showdist() //show values
{
cout << feet << "-" << inches << endl;
}
void adddist(distance, distance); //add distance through objects
};
void distance::adddist(distance d2, distance d3) //add distance
{
inches = d2.inches + d3.inches;
feet = 0;
if (inches >= 12.0)
{
inches -= 12.0;
feet++;
}
feet += d2.feet + d3.feet;
}
int main()
{
}
I'm writing a few classes for a homework assignment and I want it to be impossible for my class member functions to be called in main. If they are, I want the program to exit. How would I know when my member functions are being called?
Related
Ok so i'am writting this code for an exercise we have to write a class for matrices and then to check it we use a code that the teacher wrote to check if it performes the normal operations.
And i don't get exactly where i am wrong it seems to bother the compiler that i return a type Matrix but really i dont get what is a lvalue or rvalue .
But i get this when i try to compile
anthony#anthony-linux:~/Documents/CS/Ex6$ g++ -Wall simplematrixtest.cc Matrix.cc -o simplematrixtest
simplematrixtest.cc: In function ‘int main()’:
simplematrixtest.cc:70:24: error: cannot bind non-const lvalue reference of type ‘Matrix&’ to an rvalue of type ‘Matrix’
70 | Matrix g = f.multiply(a);
| ~~~~~~~~~~^~~
In file included from simplematrixtest.cc:4:
Matrix.hh:13:18: note: initializing argument 1 of ‘Matrix::Matrix(Matrix&)’
13 | Matrix(Matrix &m);
| ~~~~~~~~^
this is my class Matrix:
#include "Matrix.hh"
#include <cmath>
#include <iostream>
using namespace std;
// Default constructor: initializes the Matrix.
Matrix::Matrix() {
nrows=0;
ncols=0;
values=0;
}
// Initializes the Matrix with rows and cols.
Matrix::Matrix(int numberOfRows,int numberOfCols) {
nrows=numberOfRows;
ncols=numberOfCols;
values = new double[nrows*ncols] ;
for (int i = 0; i < nrows*ncols; i++) {
values[i] = 0;
}
}
// Copy constructor
Matrix::Matrix(Matrix &m)
{
nrows=m.getRows();
ncols=m.getCols();
int sizeOfM=m.getRows()*m.getCols();
values = new double[sizeOfM];
for (int i = 0; i < sizeOfM; ++i) {
values[i] = m.values[i];
}
}
// Destructor - Matrix allocates no dynamic resources.
Matrix::~Matrix() {
delete[] values;
// no-op
}
// Mutators:
void Matrix::setElem(int rowIndex,int colIndex,double val){
values[rowIndex*ncols+colIndex]=val; /*See Jasper i listen to what you say ! No return for a void function :) */
}
void Matrix::subtract(Matrix &m) {
for (int i = 0; i < nrows*ncols; i++) {
values[i] -=m.values[i];
}
}
void Matrix::add(Matrix &m) {
for (int i = 0; i < nrows*ncols; i++) {
values[i] +=m.values[i];
}
}
Matrix Matrix::multiply(Matrix &m) {
if(ncols!=m.getRows()){
cout << " Error :invalid matrix multiplication"<< endl;
Matrix ret(0,0);
return ret;
}
else{
Matrix ret(nrows,m.getCols());
for (int rowIndex = 0; rowIndex < ret.nrows; rowIndex++) {
for (int colIndex = 0; colIndex < ret.ncols; colIndex++) {
for(int count=0; count <= ncols; count++) {
ret.values[rowIndex*ncols+colIndex] +=(values[rowIndex*ncols+(count)]*m.values[count*ncols+colIndex]);
}
}
}
return ret;
}
}
// Accessors:
int Matrix::getRows() {
return nrows;
}
int Matrix::getCols() {
return ncols;
}
double Matrix::getElem(int rowIndex,int colIndex){
return values[rowIndex*ncols+colIndex];
}
bool Matrix::equals(Matrix &m) {
if(m.getRows()!=nrows||m.getCols()!=ncols){return false;}
for (int i = 0; i < nrows*ncols; i++) {
if(values[i] !=m.values[i]){return false;}
}
return true;
}
Apparently the problem is in multiply here is the test code
#include <iostream>
using namespace std;
#include "Matrix.hh"
// Have some fun playing with a Matrix!
int main(void) {
// Create a new matrix with two rows and three columns
Matrix a(2, 3);
// Print out some information about the size of this matrix:
cout << "Matrix a is " << a.getRows() << " rows tall." << endl;
cout << "Matrix a is " << a.getCols() << " columns wide." << endl;
// Print out the contents of this matrix (should be all zeroes!):
for(int r = 0; r < a.getRows(); r++) {
for(int c = 0; c < a.getCols(); c++) {
cout << "Element (" << r << ", " << c << ") = " << a.getElem(r,c) << endl;
}
}
// Fill in a few values
a.setElem(1, 2, -5280); // bottom right element is now -5280
a.setElem(0, 1, 123); // top center element is now 123
// Create an identical copy of this matrix
Matrix b = a;
// Change the original matrix some more
a.setElem(1, 2, 555); // bottom right element is now 555
// Examine some elements of each matrix
cout << "(1,2) of a = " << a.getElem(1,2) << " [should be 555]" << endl;
cout << "(1,2) of b = " << b.getElem(1,2) << " [should be -5280]" << endl;
// So if a and b are different, let's copy a into a new matrix and add b to it:
Matrix c = a;
c.add(b);
// Now let's copy c into another new matrix, d, and subtract a from it:
Matrix d = c;
d.subtract(a);
// Hmm... that means d should be b, no?
if (d.equals(b)) {
cout << "Yay! d = b!" << endl;
} else {
cout << "Uh-oh! Something went wrong, d isn't b!" << endl;
}
// Let's create a tiny 0 by 0 matrix using the default constructor:
Matrix e;
cout << "0x0 matrix e is " << e.getRows() << " by " << e.getCols() << endl;
// Of course, e and d are different, since they have different sizes!
if(!e.equals(d)) {
cout << "e and d are indeed different!" << endl;
} else {
cout << "Oh well, back to the drawing board...." << endl;
}
Matrix f(2,2);
f.setElem(0, 0, 2.0);
f.setElem(1, 0, 3.0);
f.setElem(0, 1, 5.0);
f.setElem(1, 1, 7.0);
Matrix g = f.multiply(a);
if (g.getElem(1, 2) == 3885.0) {
cout << "Multiply seems to work!" << endl;
} else {
cout << "Error in multiply() !" << endl;
}
// Okay, enough of this; destroy all those matrices and end the program:
return 0;
}
If i write
Matrix g = a ;
f.multiply(a);
The code compiles without any problem so it is a problem with this line: Matrix g =f.multiply(a);
So the objective is to create an abstract 'shape' class with 'rectangle' and 'triangle' as derived classes. Finishing the assignment with printing the perimeters and areas of a rectangle and triangle using a non-member function in main(). I'm having trouble on how to use just one non-member function, as opposed to making a print function for each type of shape:
void printPerimeter(Triangle triangle);
void printPerimeter(Rectangle rectangle);
//I'm trying not to do this
//what I had in mind, but don't know how to work this problem.
void printPerimeter(Shape shape)
{
float temp;
temp = shape.calcPerimeter();
cout << "Perimeter: " << temp << endl;
}
I know an abstract class can't be passed into a function, so how could I go about this?
class Shape
{
private:
public:
virtual void calcPerimeter()
{
cout << "Shape" << endl;
}
};
class Triangle1 : public Shape
{
public:
void calcPerimeter()
{
cout << "Triangle" << endl;
}
};
class Rectangle1 : public Shape
{
public:
void calcPerimeter()
{
cout << "Rectangle" << endl;
}
};
void printPerimeter(Shape* shape)
{
shape->calcPerimeter();
}
int main()
{
Shape *triangle = new Triangle1();
Shape *rectangle = new Rectangle1();
printPerimeter(triangle);
printPerimeter(rectangle);
return 0;
}
Please, check if this helps you to achieve your goal. Courtesy: #Retired Ninja
My Compiler gives runtime error when I initialize the float array in Veccreator function. I am here posting just a sample of what my code looks like.
#include<iostream>
using namespace std;
#define SIZE 1000
class Vector
{
private:
float vecarray[SIZE];
public:
void VecCreator(int dimension)
{
vecarray[SIZE]= { 0 };
cout << "Enter " << dimension << " digits" << endl;
for (int i = 0; i < dimension; i++)
{
cin >> vecarray[i];
}
}
};
int main(void) {
Vector obh;
obh.VecCreator(2);
}
But it works fine with this:`
#include<iostream>
using namespace std;
#define SIZE 1000
class Vector
{
private:
float vecarray[SIZE]= {0};
public:
void VecCreator(int dimension)
{
cout << "Enter " << dimension << " digits" << endl;
for (int i = 0; i < dimension; i++)
{
cin >> vecarray[i];
}
}
};
int main(void) {
Vector obh;
obh.VecCreator(2);
}
Please tell me why the first code is giving error.
Look at the second answer here:
https://social.msdn.microsoft.com/Forums/vstudio/en-US/14e7318e-6fff-4d68-a823-9cbe7b7bc20a/debugging-runtime-check-failure-2-stack-around-the-variable-loggerthread-was-corrupted?forum=vcgeneral
why not do it like here below? i mean if you want to put values in there, why initially put 0 in there?
private:
float vecarray[SIZE];
public:
void VecCreator(int dimension)
{
cout << "Enter " << dimension << " digits" << endl;
for (int i = 0; i < dimension; i++)
{
cin >> vecarray[i];
}
}
I'm doing an exercise from my textbook that has me create a program that allows the user to manage a list of favorite games by adding, deleting, or viewing the items in the vector. I made use of functions; my program runs, but the functions don't seem to be doing what they're supposed to. I'm able to input a game name for addGame(), but when I input 4 in the do/while loop, no vector is printed. Likewise, the removeGame() function doesn't seem to be working since it displays no message if I type in a game not in the list.
Which function is at fault for the lack of display? Both or just one (addGame or dispGames)? And why is my removeGame function not working?
Thanks for helping.
// exercises ch 4.cpp : main project file.
#include "stdafx.h"
#include<iostream>
#include<string>
#include<vector>
#include<iterator>
using namespace std;
void addGame(vector<string> faveGames);
void removeGame(vector<string> faveGames);
void dispGames(vector<string> faveGames);
int main(array<System::String ^> ^args)
{
vector<string> faveGames;
int choice;
cout << "Welcome to the Favorite Games List program!\n\n";
do
{
cout << "What would you like to do?\n\n";
cout << "1 - End program. \n 2 - Add new game to list. \n 3 - Remove game from list. \n 4 - Display list. \n";
cout << "Enter the corresponding number of your choice: ";
cin >> choice;
switch (choice)
{
case 1: cout << "Ending program.\n"; break;
case 2: addGame(faveGames) ; break;
case 3: removeGame(faveGames); break;
case 4: dispGames(faveGames); break;
default: "That is not a valid response, please try again.";
}
}
while(choice != 1);
return 0;
}
void addGame(vector<string> faveGames) {
string newFaveGame;
cout << "Enter the name of the game you want to add: ";
cin >> newFaveGame;
faveGames.push_back(newFaveGame);
}
void removeGame(vector<string> faveGames) {
vector<string>::iterator deletedGameIter;
string deletedGame;
cout << "Enter the name of the game you want to delete: ";
cin >> deletedGame;
for(deletedGameIter = faveGames.begin(); deletedGameIter != faveGames.end(); ++deletedGameIter) {
if(deletedGame == *deletedGameIter) {
faveGames.erase(deletedGameIter);
}
else
{
cout << "That game is not on your list.\n";
}
}
}
void dispGames(vector<string> faveGames) {
vector<string>::iterator iter;
for(iter = faveGames.begin(); iter != faveGames.end(); ++iter)
{
cout << *iter << endl;
}
}
Main problem:
You are passing faveGames by value. Any changes to faveGames don't change the variable in main.
You need to pass them by reference if you want the changes to be visible in main:
void addGame(vector<string>& faveGames);
void removeGame(vector<string>& faveGames);
There are other problems in your code that need to be cleaned up too.
Problem
You have
int main(array<System::String ^> ^args)
This is not standard C++ code. Are you using Microsoft Managed C++?
Problem
You have
faveGames.erase(deletedGameIter);
in removeGame. At that point, deletedGameIter is an invalid object. Incrementing it will lead to undefined behavior. You can change the for loop in that function to:
for(deletedGameIter = faveGames.begin();
deletedGameIter != faveGames.end();
++deletedGameIter) {
if(deletedGame == *deletedGameIter) {
faveGames.erase(deletedGameIter);
return
}
}
if you don't expect to see the game multiple times in the your list. If you expect to see it multiple times, you can use:
for(deletedGameIter = faveGames.begin();
deletedGameIter != faveGames.end(); ) {
if(deletedGame == *deletedGameIter) {
deletedGameIter = faveGames.erase(deletedGameIter);
}
else {
++deletedGameIter;
}
}
I am trying to create a Runnable interface in c++11 using packaged_task, with child class overriding run() function. I don't know why this code is not compiling. Its giving error related to type argument.
/usr/include/c++/4.8.1/functional:1697:61: error: no type named ‘type’ in ‘class std::result_of()>’
typedef typename result_of<_Callable(_Args...)>::type result_type;
Below is my code snippet. Could someone plz give me some information on this error and whether implementing Runnable this way is a right way to proceed ?
class Runnable {
public:
explicit Runnable() {
task_ = std::packaged_task<int()>(&Runnable::run);
result_ = task_.get_future();
std::cout << "starting task" << std::endl;
}
virtual int run() = 0;
int getResult() {
task_();
return result_.get();
}
virtual ~Runnable() {
std::cout << "~Runnable()" << std::endl;
}
private:
std::future<int> result_;
std::packaged_task<int()> task_;
};
class foo : public Runnable {
int fib(int n) {
if (n < 3) return 1;
else return fib(n-1) + fib(n-2);
}
public:
explicit foo(int n) : n_(n) {}
int run() {
cout << "in foo run() " << endl;
int res = fib(n_);
cout << "done foo run(), res = " << res << endl;
return res;
}
~foo() {}
private:
int n_;
};
int main(int argc, char*argv[]) {
stringstream oss;
oss << argv[1];
int n;
oss >> n;
shared_ptr<foo> obj(new foo(n));
obj->run();
cout << "done main" << endl;
return 0;
}