Print adress iinsted of values
Jul 17, 2017 at 2:13pm UTC
any can see the mistake i done?
why its printing the adress and not values?
i try to done double pointer like pointer to array of object like in darje post.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70
#pragma once
#include<iostream>
#include<cassert>
using namespace std;
class Point {
int x;
int y;
public :
Point() :x(0), y(0) {}
Point(int a, int b) :x(a), y(b) {}
Point(const Point &p) {
x = p.x;
y = p.y;
}
Point operator =(const Point &o) {
x = o.x;
y = o.y;
return *this ;
}
friend ostream &operator <<(ostream &out, const Point &p) {
out << "(" << p.x << "," << p.y << ")" << endl;
return out;
}
};
class Cpoint {
int size;
Point ** ptr;
public :
Cpoint(int size) {
this ->size = size;
ptr = new Point*[size];
assert(ptr != NULL);
}
~Cpoint() {
for (int i = 0; i < size; i++) {
delete [] ptr[i];
}
delete []ptr;
}
void set(int index, const Point &p) {
if (size > index) {
ptr[index] = new Point(p);
}
}
friend ostream &operator <<(ostream &out, const Cpoint &p) {
for (int i = 0; i < p.size; i++) {
out << p.ptr[i] << endl;
}
return out;
}
};
int main() {
Point a(1, 3);
Point b(2, 4);
Cpoint cpoint(2);
cpoint.set(0, a);
cpoint.set(1, b);
cout << cpoint;
system("pause" );
return 0;
}
Last edited on Jul 17, 2017 at 2:18pm UTC
Jul 17, 2017 at 2:25pm UTC
In class Cpoint you create an array of pointers to objects. It might be simpler to just create an array of objects:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29
class Cpoint {
int size;
Point * ptr;
public :
Cpoint(int size) {
this ->size = size;
ptr = new Point[size];
assert(ptr != NULL);
}
~Cpoint() {
delete []ptr;
}
void set(int index, const Point &p) {
if (size > index) {
ptr[index] = p;
}
}
friend ostream &operator <<(ostream &out, const Cpoint &p) {
for (int i = 0; i < p.size; i++)
out << p.ptr[i] << endl;
return out;
}
};
Alternatively, you'd need to dereference the pointers before use, but I'm not sure there's any benefit in doing things that way.
Jul 17, 2017 at 2:30pm UTC
isnt pointer to array that hold an objects?
1 2 3 4 5 6
void set(int index, const Point &p) {
if (size > index) {
ptr[index] = new Point(p);
}
}
Last edited on Jul 17, 2017 at 2:30pm UTC
Jul 17, 2017 at 2:43pm UTC
ptr
is a pointer to an array of pointers.
ptr[i]
is a pointer.
In your original code, you'd need to dereference the pointer like so:
47 48 49 50 51 52
friend ostream &operator <<(ostream &out, const Cpoint &p) {
for (int i = 0; i < p.size; i++) {
out << *p.ptr[i] << endl; // need to dereference pointer here
}
return out;
}
Jul 17, 2017 at 2:47pm UTC
Thanks my friend its helpd me alot.
do you know where i can find alot of exersice in c++ ? like folowing output of program with interhance/virtual function/exceptions ?
Topic archived. No new replies allowed.