I am learning c and I want to create two classes B and C that inherit from A. And create a constructor for both classes: B should receive a string in the constructor. C should receive a vector from B.
I also want to implement the print function for both classes. B should output the name and C should output all B names.
This is the base class :
class A {
public:
virtual void print(std::ostream& os) = 0;
virtual ~A() = default;
};
I implemented the two subclasses and when compiling the code doesn't work and with a long error, this is just a small part of the error:
test.cpp: In member function ‘virtual void C::print(std::ostream&)’:
test.cpp:34:18: error: no match for ‘operator<<’ (operand types are ‘std::ostream’ {aka ‘std::basic_ostream<char>’} and ‘__gnu_cxx::__alloc_traits<std::allocator<B>, B>::value_type’ {aka ‘B’})
34 | os << this->b[i];
In file included from /usr/include/c /9/iostream:39,
from test.cpp:1:
Here are the two subclasses :
class B : public A{
std::string name;
public:
B(std::string name) : A(), name(name){}
void print(std::ostream& os) override {
os << this->name;
}
};
class C : public A{
std::vector<B> b;
public:
C(std::vector<B> b) : A(), b(b){}
void print(std::ostream& os) override {
for(size_t i = 0; i < this->b.size(); i){
os << this->b[i];
}
}
};
int main(){
B b("b 1");
B b2{"b 2"};
B b3{"b 3"};
B b4{"b 4"};
std::vector<B> bs {b, b2, b3, b4};
C c {bs};
c.print(std::cout);
return 0;
}
CodePudding user response:
As said in the comments you have to overload the operator<<.
I would use this->b[i].print(os).
But if you want to define a operator<< for class B, you should read about the stream extraction operator. https://www.learncpp.com/cpp-tutorial/overloading-the-io-operators/
CodePudding user response:
There is no <<
stream insertion operator for B
.
You could write this->b[i].print(os);
instead, but since you have a virtual print
function, you only need to define one operator<<
for the base type:
std::ostream& operator<<(std::ostream& os, const A& a)
{
a.print(os);
return os;
}
and then you can <<
anything derived from A
.
Also, the print
function should be marked const
since you never want anything to be modified just from printing it.