The program I am making I wish to choose 2 values for an object, and then add them to a vector , my problem is I can't print them out through a function
#include <iostream>
#include <vector>
class x {
public:
x() {}
x(int x, int y)
{
std::cout << x << " " << y << " ";
}
void print_vect(std::vector<x> vect)
{
for (int i = 0; i < vect.size(); i++)
{
std::cout << vect[i] << " ";
}
}
};
int main()
{
std::vector<x> v;
v.reserve(7);
x obj(3,6);
for (unsigned i = 0; i < 6; i++) {
v.push_back(obj);
v.print_vect();
}
return 0;
}
In member function 'void x::print_vect(std::vector<x>)':
14:21: warning: comparison between signed and unsigned integer expressions [-Wsign-compare]
16:23: error: cannot bind 'std::ostream {aka std::basic_ostream<char>}' lvalue to 'std::basic_ostream<char>&&'
In function 'int main()':
29:5: error: 'class std::vector<x>' has no member named 'print_vect'
Looks like two errors.
Line 29. v.print_vect();
The v is a vector. There is no vector::print_vect().
The 'v' has elements. Each element has member void x::print_vect(std::vector<x>)
However, calling v[i].print_vect(); would be an error too, because there is no void x::print_vect(std::vector<x>). Which vector do you want to pass to the function?
Line 16: std::cout << vect[i]
The type of vect[i] is x. what do you want to happen in:
Line 14: You're trying to print an object of type x. Your class doesn't know how to do that.
On top of that, your class doesn't contain any data to be printed.
Line 27: You construct obj with 3 and 6. Those values are printed by the constructor, but not saved.
Line 30, you call print_vect, but don't pass an argument. print_vect requires one argument.
The traditional way to print an object is using a friend function: