I have an error in my code, I want to display the sume of 2 objects with pointers in a class. Please help me to fix it, maybe is due to the pointers. Can you see what's wrong?
This is the error:
<source>(79): error C2280: 'Pair &Pair::operator =(const Pair &)': attempting to reference a deleted function
<source>(60): note: compiler has generated 'Pair::operator =' here
<source>(60): note: 'Pair &Pair::operator =(const Pair &)': function was implicitly deleted because 'Pair' has a user-defined move constructor
#define _CRT_SECURE_NO_WARNINGS
#include <iostream>
using namespace std;
class Pair {
int *x, *y;
public:
Pair() {
x = new int(sizeof(x));
y = new int(sizeof(y));
*x = 0;
*y = 0;
}
Pair(int a, int b) {
x = new int(sizeof(x));
y = new int(sizeof(y));
*x = a;
*y = b;
}
Pair(Pair& ob) {
x = new int(sizeof(ob.x));
y = new int(sizeof(ob.y));
*x = *(ob.x);
*y = *(ob.y);
}
Pair(Pair&& ob) {
x = new int(sizeof(ob.x));
y = new int(sizeof(ob.y));
*x = *(ob.x);
*y = *(ob.y);
}
Pair(int a):Pair(a, 0) {
}
void setX(int X) {
*x = X;
}
void setY(int Y) {
*y = Y;
}
int* getX() {
return x;
}
int* getY() {
return y;
}
~Pair() {
delete[]x;
delete[]y;
}
Pair sume(Pair ob1){
Pair ob2;
*(ob2.x) = *(ob1.x) + (*x);
*(ob2.y) = *(ob1.y) + (*y);
return ob2;
}
double media() {
return (double(*x) + double(*y)) / 2;
}
};
int main() {
Pair ob1, ob2(5), ob3(4, 3);
ob1.setX(6);
ob1.setY(7);
cout << "X= " << *(ob1.getX())<<endl;
cout << "Y= " << *(ob1.getY())<<endl;
cout << "Media este: " << ob1.media();
cout << "\nX= " << *(ob2.getX()) << endl;
cout << "Y= " << *ob2.getY() << endl;
cout << "Media este: " << ob2.media();
cout << "\nX= " << *(ob3.getX()) << endl;
cout << "Y= " << *(ob3.getY()) << endl;
cout << "Media este: " << ob3.media();
Pair ob4,ob5,ob6;
ob4 = ob1.sume(ob2);//here the compiler shows the error
cout <<"\nX= "<< *(ob4.getX())<<endl;
cout << "Y= " << *(ob4.getY())<<endl;
}
Related
my english not good ,sorry.
clion class variable not initialized why appear z =16
and vs2019 situation not same
#include <iostream>
using namespace std;
class bas {
public:
int showget();
private:
int x, z, y;
};
int main() {
bas B;
B.showget();
return 0;
}
int bas::showget() {
cout << x << " " << " " << z << " " << y << "\n";
int *t;
t = &x;
cout << t<<"\n";
t = &y;
cout << t<< "\n";
t = &z;
cout << t;
return 0;
}
}
}
enter image description here
I am doing a program to test swapping couple of things by reference.
I managed to get the first two functions in my code to work but can't get to change the char * in the third function.
I think the problem is that it's a constant and only valid to read-only
that's what the error is telling me but How to be able to work with it in this way?
Here is the code:
#include <iostream>
using namespace std;
void swapping(int &x, int &y)
{
int temp =x;
x=y;
y=temp;
}
void swapping(float &x, float &y)
{
float temp=x;
x=y;
y=temp;
}
void swapping(const char *&x,const char *&y)
{
int help = *x;
(*x)=(*y);
(*y)=help;
} // swap char pointers
int main(void) {
int a = 7, b = 15;
float x = 3.5, y = 9.2;
const char *str1 = "One";
const char *str2 = "Two";
cout << "a=" << a << ", b=" << b << endl;
cout << "x=" << x << ", y=" << y << endl;
cout << "str1=" << str1 << ", str2=" << str2 << endl;
swapping(a, b);
swapping(x, y);
swapping(str1, str2);
cout << "\n";
cout << "a=" << a << ", b=" << b << endl;
cout << "x=" << x << ", y=" << y << endl;
cout << "str1=" << str1 << ", str2=" << str2 << endl;
return 0;
}
As suggested in the comments:
void swapping(const char*& x, const char*& y)
{
auto t = x;
x = y;
y = t;
}
Now you should consider to use a template:
template<typename Type>
void swapping(Type& a, Type& b)
{
auto t = a;
a = b;
b = t;
}
How do I make it so I dont have to manually delete the pointer?
With unique_ptr in the vector<> ?
Here is my code:
class vec2 {
public:
double x;
double y;
vec2() {
x = 0.0;
y = 0.0;
}
vec2(double xx, double yy) {
x = xx;
y = yy;
cout << "constructor called" << endl;
}
~vec2() {
static int count = 0;
cout << "destructor " << count << endl;
count++;
}
virtual double Length() { return sqrt(x * x + y * y); }
bool operator==(vec2& v) { return x == v.x && y == v.y; }
virtual string toString() {
stringstream s("");
s << "[" << x << " " << y << "]";
return s.str();
}
};
int main() {
vector<vec2*> vecs;
vecs.push_back(new vec2(1.8, 1.7));
vecs.push_back(new vec2(1.99, 1.7));
for (vec2* v : vecs) {
cout << v->toString() << endl;
delete v;
}
}
http://www.xgdev.com/notepad/textfiles/37631a.txt
Simple:
std::vector<std::unique_ptr<vec2>> vecs;
vecs.reserve(2); // Optional
vecs.push_back(std::make_unique<vec2>(1.8 ,1.7));
vecs.push_back(std::make_unique<vec2>(1.99, 1.7));
for (auto& v : vecs) {
cout << v->toString() << endl;
}
If you have virtual member function(s), most probably, destructor should also be virtual.
This question already has answers here:
What is The Rule of Three?
(8 answers)
Closed 7 years ago.
I have the following code:
The problem is when I create a list in main of type: Reteta.
After I display the list I receive am error of bad allocation. If I comment the destructor from the class Reteta the program works. Can you help me find the bug? Or maybe I didn't display the list well so the program have other problems to take care of.
Here is the code:
#include<iostream>
#include<fstream>
#include<list>
using namespace std;
class Medicament{
private:
char *denumire;
float pret;
public:
Medicament()
{
this->pret = 0;
this->denumire = new char[strlen("Fara denumire")];
strcpy(this->denumire, "Fara denumire");
}
Medicament(char* denumire, float pret)
{
this->denumire = new char[strlen(denumire) + 1];
strcpy(this->denumire, denumire);
this->pret = pret;
}
Medicament(const Medicament& x)
{
this->denumire = new char[strlen(x.denumire) + 1];
strcpy(this->denumire, x.denumire);
this->pret = x.pret;
}
~Medicament()
{
if (this->denumire)
{
delete[] this->denumire;
}
}
void setDenumire(char *x)
{
if (x)
{
if (this->denumire)
{
delete[] this->denumire;
}
this->denumire = new char[strlen(x) + 1];
strcpy(this->denumire, x);
}
}
char* getDenumire()
{
return this->denumire;
}
void setPret(float f)
{
if (f)
{
this->pret = f;
}
}
Medicament operator=(Medicament x)
{
this->denumire = new char[strlen(x.denumire) + 1];
strcpy(this->denumire, x.denumire);
this->pret = x.pret;
return *this;
}
friend ostream& operator<<(ostream& consola, Medicament &x)
{
consola << "Medicament: " << x.denumire << endl; //error here
consola << "Pret: " << x.pret << endl;
return consola;
}
float getPret()
{
return this->pret;
}
friend class Reteta;
};
class Reteta{
protected:
Medicament *medicamente;
int n;
public:
Reteta()
{
this->n = 0;
this->medicamente = NULL;
}
Reteta(Medicament *v, int n)
{
this->n = n;
this->medicamente = new Medicament[n];
for (int i = 0; i < n; i++)
{
this->medicamente[i] = v[i];
}
}
~Reteta()
{
if (this->medicamente)
{
delete[] this->medicamente; //The problem is here. If I comment this the program works.
}
}
int getN()
{
return this->n;
}
friend ostream& operator<<(ostream& consola, Reteta& x)
{
consola << "Numar de medicamente: " << x.n << endl;
consola << " -->Lista Medicamente<-- "<<endl;
for (int i = 0; i < x.n; i++)
{
consola << x.medicamente[i].getDenumire() <<endl; //error at this line when I compile
consola << x.medicamente[i].getPret()<< endl;
}
return consola;
}
void adaugaMedicament(Medicament x)
{
Reteta y;
y.medicamente= new Medicament[this->n+1];
for (int i = 0; i < this->n; i++)
{
y.medicamente[i] = this->medicamente[i];
}
y.medicamente[this->n] = x;
delete[] this->medicamente;
this->medicamente = new Medicament[this->n + 1];
this->n++;
for (int i = 0; i < this->n; i++)
{
this->medicamente[i] = y.medicamente[i];
}
}
Medicament operator[](int i)
{
if (i >= 0 && i < this->n)
{
return this->medicamente[i];
}
}
friend class RetetaCompensata;
virtual float getValoare()
{
float sum = 0;
for (int i = 0; i < this->n; i++)
{
sum=sum+this->medicamente[i].getPret();
}
return sum;
}
friend ifstream& operator>>(ifstream& consola, Reteta& x)
{
char aux[30];
float z;
consola >> x.n;
if (x.medicamente)
delete[] x.medicamente;
x.medicamente = new Medicament[x.n];
for (int i = 0; i < x.n; i++)
{
consola >> aux >> z;
Medicament m(aux, z);
x.medicamente[i] = m;
}
return consola;
}
};
class RetetaCompensata : public Reteta{
private:
float procentCompensat;
public:
RetetaCompensata(float procent)
{
this->procentCompensat = procent;
}
RetetaCompensata(Reteta r, float procent)
{
this->procentCompensat = procent;
this->n = r.n;
this->medicamente = new Medicament[r.n];
for (int i = 0; i < r.n; i++)
{
this->medicamente[i] = r.medicamente[i];
}
}
float getValoare()
{
float sum = 0;
sum = this->procentCompensat*this->getValoare();
return sum;
}
friend ostream& operator<<(ostream& consola, RetetaCompensata &x)
{
consola << "**Procent compensat: " << x.procentCompensat << endl;
consola << "Numar de medicamente: " << x.n << endl;
consola << " -->Lista Medicamente<-- " << endl;
for (int i = 0; i < x.n; i++)
{
consola << x.medicamente[i] << " ";
}
return consola;
}
};
void main()
{
//1
Medicament nurofen("Nurofen", 11.25f);
Medicament aspirina = nurofen;
aspirina.setDenumire("Aspirina");
aspirina.setPret(4.5f);
Medicament bixtonim("Bixtonim", 8.2f);
Medicament temp;
temp = nurofen;
cout << temp << endl;
cout << nurofen << endl;
cout << aspirina << endl;
//2
Medicament medicamente[] = { aspirina, nurofen };
Reteta r0(medicamente, 2);
cout << r0 << endl;
//3
Reteta r1;
r1.adaugaMedicament(nurofen);
r1.adaugaMedicament(aspirina);
for (int i = 0; i < r1.getN(); i++)
{
cout << r1[i] << endl;
}
//4
RetetaCompensata r2(0.5);
r2.adaugaMedicament(bixtonim);
r2.adaugaMedicament(aspirina);
RetetaCompensata r3(r1, 0.2);
cout << "AFISARE R3" << endl;
cout << r3 << endl << endl;
Reteta* p = &r1;
cout <<"Valoare reteta r1: "<< p->getValoare() << endl;
//5
Reteta r4;
ifstream fisier("retete.txt");
fisier >> r4;
cout << r4 << endl;
//6
cout << endl << "Afisare Lista :" << endl << endl << endl;
list<Reteta> R;
list<Reteta>::iterator it;
R.push_back(r0);
R.push_back(r1);
R.push_back(r3);
R.push_back(r2);
R.push_back(r4);
for (it = R.begin(); it != R.end(); it++)
{
cout << *it << " Valoare Reteta: " << it->getValoare() << endl << endl << endl; // error at this line when I compile
}
}
This is a memory overwrite:
this->denumire = new char[strlen("Fara denumire")];
strcpy(this->denumire, "Fara denumire");
You are not allocating room for the terminating null character:
this->denumire = new char[strlen("Fara denumire") + 1];
strcpy(this->denumire, "Fara denumire");
But why do this when you have std::string available? That alone not only alleviates errors like this, but you don't need to write assignment operators, copy constructor, or destructor for your Medicament class.
The other error is that your Reteta class lacks a copy constructor and assignment operator, thus it is not safely copyable due to the Medicament* member. You are then using this class as a type in std::list<Reteta>.
Since Reteta is not safely copyable, and std::list makes copies, you enter the world of undefined behavior. Thus you must provide appropriate copy / assignment operators for the Reteta class.
This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
What are copy elision and return value optimization?
I have the following program:
#include <iostream>
using namespace std;
class Pointt {
public:
int x;
int y;
Pointt() {
x = 0;
y = 0;
cout << "def constructor called" << endl;
}
Pointt(int x, int y) {
this->x = x;
this->y = y;
cout << "constructor called" << endl;
}
Pointt(const Pointt& p) {
this->x = p.x;
this->y = p.y;
cout << "copy const called" << endl;
}
Pointt& operator=(const Pointt& p) {
this->x = p.x;
this->y = p.y;
cout << "op= called" << endl;
return *this;
}
};
Pointt func() {
cout << "func: 1" << endl;
Pointt p(1,2);
cout << "func: 2" << endl;
return p;
}
int main() {
cout << "main:1" << endl;
Pointt k = func();
cout << "main:2" << endl;
cout << k.x << " " << k.y << endl;
return 0;
}
The output I expect is the following:
main:1
func: 1
constructor called
func: 2
copy const called
op= called
main:2
1 2
But I get the following:
main:1
func: 1
constructor called
func: 2
main:2
1 2
The question is: why doesn't returning an object from func to main call my copy constructor?
This is due to Return Value Optimization. This is one of the few instances where C++ is allowed to change program behavior for an optimization.