I am compiling these programs. Complex.h, Complex.cpp, and project1_task1.cpp on centOS I compile this fine in visual studio, but I get the error in centOS. this is for a class.
Complex.h
#ifndef COMPLEX_H
#define COMPLEX_H
class Complex
{
private:
double realPart;
double imaginaryPart;
public:
Complex(double real = 0, double imag = 0); //constructor that initializes the complex number by default arguments
double getReal(); //get function that returns the real part of the complex number
double getImag(); //get function that returns the imaginary part of the complex number
void setReal(double real); //set function that sets the real part of the complex number
void setImag(double imag); //set function that sets the imaginary part of the complex number
void print(); //function that displays the complex number
};
#endif
Complex.cpp
#include <iostream>
#include "Complex.h"
using namespace std;
Complex::Complex(double real, double imag)
{
realPart = real;
imaginaryPart = imag;
}
double Complex::getReal() {
return this->realPart;
}
double Complex::getImag() {
return this->imaginaryPart;
}
void Complex::setReal(double real) {
realPart = real;
}
void Complex::setImag(double imag) {
imaginaryPart = imag;
}
void Complex::print() {
if (realPart != 0)
cout << realPart;
if (imaginaryPart != 0)
{
if (imaginaryPart == 1)
cout << "+i";
else if (imaginaryPart == -1)
cout << "-i";
else if (imaginaryPart > 0 && realPart != 0)
cout << " + " << imaginaryPart << "i";
else
cout << imaginaryPart << "i";
}
cout << endl;
}
here is project1_task1.cpp
#include <iostream>
#include"complex.h"
using namespace std;
int main()
{
Complex c;
c.setReal(2);
c.setImag(3);
c.print();
Complex c1(4);
c1.setImag(5);
c1.print();
Complex c2(6, 7);
c2.print();
return 0;
}
I keep getting Complex not defined in project1_task1.cpp when I compile in centOs.
how can I fix this?
Since linux filesystem are usually case sensitive, then do in
project1_task1.cpp
replace the
#include"complex.h"
with
#include"Complex.h"
Related
Unit testing means writing code that verifies individual parts, or units, of an application or library. A unit is the smallest testable part of an application. Unit tests assess code in isolation. In C++ this means writing tests for methods or functions.
I am writing a basic calculator program and trying to use CPPUnitTest to test the code in Visual studio 2019.After that I have to build this in Jenkins too.
Please don't judge .. I am writing unit Test for the 1st time ..
this is my Calculator.cpp
#include <iostream>
#include "Calc.h"
using namespace std;
int main()
{
Calc obj;
float a, b;
cin >> a >> b;
int menu;
cout << "Enter what operation you want(1-4);" << endl;
cout << "1. Addition" << endl;
cout << "2. Subtraction" << endl;
cout << "3. Multiplication" << endl;
cout << "4. Division" << endl;
cin >> menu;
switch (menu)
{
case 1:obj.add(a, b);
break;
case 2:obj.sub(a, b);
break;
case 3:obj.multiply(a, b);
break;
case 4:
try
{
obj.divide(a, b);
}
catch (std::runtime_error& e)
{
cout << e.what() << "\n";
}
break;
default:
{
cout << "Invalid input" << endl;
}
}
}
This is class Calc or "Calc.h"
Here I have used std::runtime_error to throw error on division bye zero
#pragma once
#include <stdexcept>
class Calc {
public:
float add(float a, float b)
{
return a + b;
}
float sub(float a, float b) {
return a - b;
}
float multiply(float a, float b) {
return a * b;
}
float divide(float a, float b) {
if (b == 0)
{
throw std::runtime_error("Division by zero condition!");
}
return a / b;
}
};
I am trying to write unit test using CPPUnitTest for my code.
I have written code for add and subtract using assert::AreEqual but for divide by zero condition, I don't know to write the test case.
this is my unit test code.
#include "pch.h"
#include "CppUnitTest.h"
#include "../Calculator/Calc.h"
#include <stdexcept>
using namespace std;
using namespace Microsoft::VisualStudio::CppUnitTestFramework;
namespace CalculatorTest
{
TEST_CLASS(CalculatorTest)
{
public:
Calc cal;
TEST_METHOD(AddTest)
{
float k = cal.add(3, 4);
Assert::AreEqual(7.0f,k);
}
TEST_METHOD(SubTest)
{
float k = cal.sub(3, 4);
Assert::AreNotEqual(-2.0f, k);
}
TEST_METHOD(DivByZeroTest)
{
//what should I write here
}
};
}
Please help me to write the test method for this .
Somewhere I read CPPUNIT_ASSERT_THROW(cal->divide(12,0), std::runtime_error); but this is not working in my case. How can I make Assert::AreEqual
Also suggest which else method I can use to increase my code coverage.
You should not use assert::AreEqual when checking for exceptions.
You could wrap your exception throwing code in a lambda and pass it to Assert::ExpectException<std::runtime_error>, which should assert true if the expected exception is thrown:
TEST_METHOD(DivByZeroTest)
{
auto func = [] { return cal.divide(1.f, 0.f); };
Assert::ExpectException<std::runtime_error>(func);
}
I expect that this does something like this internally::
bool result = false;
try {
func();
} catch(const std::runtime_error&) {
result = true;
} catch(...) {
}
return result;
This occurs for my first member function for the class 'complex_test' (the constructor) so I assume I'm getting the same error for the rest of the functions.
FULL ERROR:error: 'complex_test' does not name a type.
The class implementation file below:
#include <fstream> // For ifstream, ofstream classes
#include "Complex.hpp" // For complex class declaration
#include "ComplexTest.hpp" // For complex_test class declaration
complex_test::complex_test()
{
}
void complex_test::run()
{
std::ifstream fin("complex-in.txt");
std::ofstream fout("complex-out.txt");
int n; fin >> n;
for (int testcase = 0; testcase < n; ++testcase) {
run_test(fin, fout);
}
// Close the input and output files.
fin.close();
fout.close();
}
void complex_test::run_test(ifstream& fin, ofstream& fout)
{
// Read the four double values.
double real1, imag1, real2, imag2;
fin >> real1 >> imag1 >> real2 >> imag2;
complex c1(real1, imag1);
complex c2(real2, imag2);
complex sum = c1.add(c2);
complex diff = c1.sub(c2);
complex product = c1.mul(c2);
complex quotient = c1.div(c2);
fout << "c1 = " << c1.to_string() << ", c2 = " << c2.to_string() << std::endl;
fout << "c1 + c2 = " << sum.to_string() << std::endl;
fout << "c1 - c2 = " << diff.to_string() << std::endl;
fout << "c1 * c2 = " << product.to_string() << std::endl;
fout << "c1 / c2 = " << quotient.to_string() << std::endl;
}
The class header for complex_test class:
#ifndef COMPLEX_HPP
#define COMPLEX_HPP
#include <fstream>
using namespace std;
class complex_test {
public:
complex_test();
void run();
private:
void run_test(ifstream& fin, ofstream& fout);
};
#endif
In addition to this I get an error in the function implementation for the class 'complex' in line 62 for the get_real(), the compiler says it is not in scope, yet I defined it in the very same file?
Exact wording of error: 'get_real' was not declared in this scope.
#include <iomanip> // For fixed, setprecision()
#include <sstream> // For stringstream class
#include "Complex.hpp" // For the complex class declaration
#include <cmath>
complex::complex()
{
init(0,0);
}
complex::complex(double init_real, double init_imag)
{
init(init_real, init_imag);
}
double complex::get_imag()
{
return m_imag;
}
double complex::get_real()
{
return m_real;
}
void complex::init(double init_real, double init_imag)
{
m_real = init_real;
m_imag = init_imag;
}
void complex::set_imag(double s)
{
m_imag = s;
}
void complex::set_real(double s)
{
m_real = s;
}
std::string complex::to_string()
{
std::stringstream sout;
sout << std::fixed << std::setprecision(4);
sout << "(" << get_real();
double imag = get_imag();
if (imag < 0) {
sout << " - " << -imag << 'i';
} else if (imag > 0) {
sout << " + " << imag << 'i';
}
sout << ")";
return sout.str();
}
complex complex::add(complex& rhs_op)
{
double sum_real = get_real() + rhs_op.get_real();
double sum_imag = get_imag() + rhs_op.get_imag();
complex sum(sum_real, sum_imag);
return sum;
}
complex complex::div(complex& rhs_op)
{
complex inverse = rhs_op.invert();
complex quotient = mul(inverse);
return quotient;
}
complex invert()
{
double denom = std::pow(get_real(), 2) + std::pow(get_imag(), 2);
double inv_real = get_real() / denom;
double inv_imag = get_imag() / denom;
complex inverse(inv_real, inv_imag);
return inverse;
}
complex complex::mul(complex& rhs_op)
{
double prob_real = get_real() * rhs_op.get_real() - (get_imag() * rhs_op.get_imag());
double prod_imag = get_imag() * rhs_op.get_real() + (get_real * rhs_op.get_imag());
complex product(prod_real, prod_imag);
return product;
}
complex complex::negate()
{
complex neg(-get_real, -get_imag);
return neg;
}
complex complex::sub(complex& rhs_op)
{
complex negation = rhs_op.negate();
complex diff = add(negation);
return diff;
}
The header file for class 'complex':
#ifndef COMPLEX_HPP
#define COMPLEX_HPP
#include <string>
class complex
{
public:
complex();
complex(double,double);
complex add(complex&);
complex div(complex&);
complex invert();
complex mul(complex&);
complex negate();
complex sub(complex&);
double get_imag();
double get_real();
void set_imag(double);
void set_real(double);
std::string to_string();
private:
void init(double , double );
double m_real;
double m_imag;
};
#endif
The first two lines of both of the shown header files appear to be:
#ifndef COMPLEX_HPP
#define COMPLEX_HPP
Which means that including either header file will make subsequent inclusion of the other header file a big fat nothing.
P.S. You will also remove more possibilities of other mysterious compilation errors by immediately forgetting that "using namespace std;" is a part of the C++ language. Do yourself a favor and completely get rid of it, especially in header files. It will take a little bit of time getting used it to it, but explicitly referencing the std namespace every time it's needed will quickly become second nature, and mostly an automatic, subconscious process, very quickly.
In below program I am getting 2 errors at below lines.
r = sum(p,q); //Function sum should have a prototype.
r = sum(p,q); //Cannot convert int to complex
Kindly advise the changes in the code.
Note: I have to do the code by passing objects of complex class to add and also the addition should return a complex number.
#include<iostream.h>
#include<conio.h>
class Complex
{
private:
int real;
int imag;
public:
void getNo()
{
cout<<"Enter real part : "<<endl;
cin>>real;
cout<<"Enter imaginary part : "<<endl;
cin>>imag;
}
void showNo()
{
cout<<real<<"+"<<imag<<"i";
}
Complex sum(Complex, Complex);
};
Complex Complex :: sum(Complex c1, Complex c2)
{
Complex a;
a.real = c1.real + c2.real;
a.imag = c1.imag + c2.imag;
return a;
}
void main()
{
clrscr();
Complex p,q,r,s;
p.getNo();
q.getNo();
cout<<endl<<"First complex number is : ";
p.showNo();
cout<<endl<<"Second complex number is : ";
q.showNo();
r = sum(p,q);
cout<<"Addtion of the complex no is : ";
r.showNo();
getch();
}
For your purpose the "sum" function should not be in the "Complex" class. Here a bit changed code:
#include <iostream>
#include <conio.h>
using namespace std;
class Complex
{
public:
int real;
int imag;
void getNo ()
{
cout << "Enter real part : " << endl;
cin >> real;
cout << "Enter imaginary part : " << endl;
cin >> imag;
}
void showNo ()
{
cout << real << "+" << imag << "i";
}
};
Complex sum (Complex c1, Complex c2);
int main ()
{
//clrscr ();
Complex p, q, r, s;
p.getNo ();
q.getNo ();
cout << endl << "First complex number is : ";
p.showNo ();
cout << endl << "Second complex number is : ";
q.showNo ();
r = sum (p, q);
cout << endl << "Addtion of the complex no is : ";
r.showNo ();
getch ();
}
Complex sum (Complex c1, Complex c2)
{
Complex
a;
a.real = c1.real + c2.real;
a.imag = c1.imag + c2.imag;
return a;
}
Edit
Functions in class require an instance (object) of class.
Simply you CAN do this:
p.getNo();
t.sum();
myComplexNum.getReal();
But in your code you are trying to do this which you CAN NOT:
a = getNo();
b = sum();
getReal();
Additionally you CAN make the function static like other answer.
static functions and variables does not require an instance. Calling:
// We have 1 Box named b
Box b;
b.setHeight(5);
b.setWidth(3);
b.setDepth(3);
//ClassName::StaticVariable;
int c1 = Box::count; // returns 1
//ClassName::StaticFunction(Parameters);
int c2 = Box::getCount(); // returns 1
When you declare a function (a method) in a class, this method can be called on a instance of this class (a object).
In the given code the function Complex sum (Complex c1, Complex c2); should be called on an object of type Complex.
But as the function doesn't change anything inside the object, it rather creates a new object and returns it, you should better declare a static method.
static Complex sum(Complex, Complex);
in this case you can call the function without an existing Complex object.
The syntax is the following :
r = Complex::sum(a, b);
I am trying to add 2 complex numbers together, but i am getting the errors:
no operator "+" matches these operands
no operator "<<" matches these operands
#include <iostream>
using namespace std;
class complex
{
public:
double get_r() { return r; }
void set_r(double newr) { r=newr; }
double set_i() { return i; }
void set_i(double newi) { i = newi; }
private:
double r, i;
};
int main()
{
complex A, B;
A.set_r(1.0);
A.set_i(2.0);
B.set_r(3.0);
B.set_i(2.0);
complex sum = A+B;
cout << "summen er: " << sum << endl;
system("PAUSE");
return 0;
};
I'm very new to programming, but i can't see why it won't add these numbers together. What have I done wrong?
You must overload operators + and << (and each one in your need) for your defined classes. Note that operators are no more than specific functions with specific definition syntax (operator+, for example: C = A + B could be understood as C = A.sum(B)). Here a link about http://en.cppreference.com/w/cpp/language/operators
Operator + is defined for builtin types and for some types from the standard library. As complex is here a custom class, you must define all operators that should act on it.
operator + could be defined as:
class complex {
...
complex operator + (const complex& other) {
return complex(get_r() + other.get_r(), get_i() + other.get_i());
}
...
};
Beware that does allow neither A++ nor A-B. They would require (resp.) complex & operator ++() or complex operator - (const complex &).
For stream insertion, the first parameter is the stream itself, so you must define a friend operator with 2 parameters outside the class:
outstream& opererator << (outstream &out, const complex& val) {
// output it the way you want
return out;
}
Complex numbers are part of the C++ standard. Here is the example from http://en.cppreference.com/w/cpp/numeric/complex.
#include <iostream>
#include <iomanip>
#include <complex>
#include <cmath>
int main()
{
using namespace std::complex_literals;
std::cout << std::fixed << std::setprecision(1);
std::complex<double> z1 = 1i * 1i;
std::cout << "i * i = " << z1 << '\n';
std::complex<double> z2 = std::pow(1i, 2);
std::cout << "pow(i, 2) = " << z2 << '\n';
double PI = std::acos(-1);
std::complex<double> z3 = std::exp(1i * PI);
std::cout << "exp(i * pi) = " << z3 << '\n';
std::complex<double> z4 = 1. + 2i, z5 = 1. - 2i;
std::cout << "(1+2i)*(1-2i) = " << z4*z5 << '\n';
}
Trying to implement a class complex yourself would require you define addition, equality, and ostream. And you would only have 5% of a fully implemented class. Looking at the header itself will reveal how those that wrote the C++ standard library implemented the whole thing.
All the arithmetic operators like plus, minus, multiply or divide only work with pre defined data types, like int, char, float etc.
Now if you want to add something in a class, you have to use the fundamental aspect of OO programming that is operator overloading.
Here is how you can achieve it.
#include <iostream>
using namespace std;
class complex
{
float x, y;
public:
complex()
{
}
complex(float real, float img)
{
x = real;
y = img;
}
friend complex operator+(complex,complex);
void display(void);
};
complex operator+(complex c,complex d)
{
complex t;
t.x = d.x + c.x;
t.y = d.y + t.y;
return(t);
};
void complex::display(void)
{
cout << x << "+i" << y << endl;
}
int main()
{
complex c1, c2, c3;
c1 = complex(2.5, 3.5);
c2 = complex(1.5, 5.5);
c3 = c1 + c2;//c3=opra+(c1,c2)
cout << "C1:" << endl;
c1.display();
cout << "C2:" << endl;
c2.display();
cout << "C3:" << endl;
c3.display();
}
I'm taking a class in C++ and I've run into a problem. We have to create a list of bankaccounts that each have their own savings and checking account. I've come quite far, but now I have to use "ofstream& fout" to print the checking and savings of an imaginairy account.
My header file of "Account.h" looks like this (I think it's correct):
#include <iostream>
#include <cmath>
#include <fstream>
#ifndef ACCOUNT_H
#define ACCOUNT_H
using namespace std;
class Account{
protected:
string number;
double balance;
public:
Account(){}
Account(string nr, double bl);
void deposit(double am);
string get_number();
double get_balance();
double withdraw(double am);
bool equals(Account other);
virtual void print();
void println();
void println(string s);
virtual void println(ofstream& fout);
virtual void read(ifstream& fin);
};
#endif
My definition file is where it all goes horribly wrong with the fstream part:
#include "Account.h"
Account::Account(string nr, double bl){
if (bl >= 0){
number = nr;
balance = bl;
}
else{
number = "incorrect";
}
}
void Account::deposit(double am){
if (am >= 0){
balance = balance + am;
}
}
string Account::get_number(){
return number;
}
double Account::get_balance(){
return balance;
}
double Account::withdraw(double am){
if (0 <= am && am <= get_balance()){
balance = balance - am;
return am;
}
else{
return 0;
}
}
bool Account::equals(Account other){
if (number == other.get_number()){
return true;
}
return false;
}
void Account::print(){
cout << "<Account(" << number << ",";
cout << balance << ")>" ;
}
void Account::println(){
print();
cout << endl;
}
void Account::println(string s){
cout << s;
println();
}
void Account::println(ofstream& fout){
fout << number << ",";
fout << balance;
fout << endl;
}
void Account::read(ifstream& fin){
fin >> number;
}
There is something wrong with the declaration of void Account::println(ofstream& fout). It gives me the output
<Account(number,balance,0)>
instead of
<Account(number,balance)>
Why does this happen? I have many more problems with the printing of the savings and checking numbers, but i feel if I understand why this is happening I can solve those. Thank you to anyone who wants to help me.
Account::println(ofstream&) will print "", but since the balance is a double, it prints with a decimal place:
if balance == 0.0, it will be printed as eiter 0.0 or 0,0, depending on your locale.
Either way, you have way too many print methods, and I think the solution should be implemented through an output operator:
Header:
class Account {
// ....
// no print methods defined
};
std::ostream& operator <<(std::ostream& out, const Account& a);
Source:
std::ostream& operator <<(std::ostream& out, const Account& a)
{
return out << "";
}
Client code:
#include <iostream> // console
#include <fstream> // file
Account a;
// print to console
std::cout << a << std::endl;
// print to file
std::ofstream fout("./account.txt");
fout << a << std::endl;