C++ Dynamic Constructor -
i'm getting error:
no operator "[]" matches these operands
for line:
cout << a[j].display(n)
but when take out [j]
, i'm getting error:
class "list" has no member "display"
here code:
class list { protected: int *p; // pointer list int size; // dimension public: list(int x) { size = x; p = new int[size]; } void get(int i, int val) { p[i] = val; } }; class dlist : public list { public: int display(int i) { return p[i]; } }; int main() { int n; cout << "enter elements in row\n"; cin >> n; list a(n); int j, val; (j = 0; j < n; j++) { cin >> val; a.get(j, val); } cout << "\n"; cout << "list of elements :\n"; cout << "----------------------\n"; (j = 0; j < n; j++) cout << a[j].display(j) << "\t"; cout << "\n"; return 0; }
please help!
the class list
indeed has no member function display
. class dlist
declared like
class dlist : public list //...
has such member function. object a
defined in main object of class list
list a(n);
moreover can not create object of type dlist
because have define explicitly constructor of type.
if want use polymorphism introduce virtual functions making example member function display
virtual.
also syntax
cout << a[j].display(j) << "\t"; ^^^^^^^^^^^^^^
is incorrect because object a
scalar object. not array of objects , class has no overloaded operator []
.
you should start defining explicitly virtual destructor (otherwise there can memory leak in program) delete dynamically allocated memory in constructor parameter, copy constructor , copy assignment operator in class list. can define subscript operator , on.
Comments
Post a Comment