Accessing a nonmember function of a derived class from a base class
I'm trying to call a nonmember function of a derived class from a base class, but getting this error:
error: no matching function for call to 'generate_vectorlist(const char&)'
Here's the relevant code snippets from the base class:
//Element.cpp
#include "Vector.h"
...
string outfile;
cin >> outfile;
const char* outfile_name = outfile.c_str();
generate_vectorlist(*outfile_name); //ERROR
...
and the derived class (this is a template class, so everything's in the header):
//Vector.h
template <class T>
void generate_vectorlist(const char* outfile_name = "input.txt" )
{
std::ofstream vectorlist(outfile_name);
if (vectorlist.is_open())
for (Element::vciter iter = Element::vectors.begin(); iter!=Element::vectors.end(); iter++)
{
Vector<T>* a = new Vector&开发者_Python百科lt;T>(*iter);
vectorlist << a->getx() << '\t' << a->gety() << '\t'<< a->getz() << std::endl;
delete a;
}
else { std::cout << outfile_name << " cannot be opened." << std::endl;}
vectorlist.close();
}
My guess is there's just a small syntax thing that I'm missing. Any ideas?
You're dereferencing the pointer so you're passing a const char, not a const char*.
try this:
generate_vectorlist(outfile_name);
You have two problems:
generate_vectorlist
takes aconst char *
, not aconst char &
.The template type is not in the function signature so the compiler can not deduce the type therefore you need to specify it (using
int
in my example).
So you need to do:
generate_vectorlist<int>(outfile_name);
In the first bit, try: generate_vectorlist(outfile_name);
You should be passing a character pointer, not a character.
You need to specify the template argument. There's nothing the compiler can use to deduce what type T
is. So you'll have to call it like generate_vectorlist<MyType>(outfile_name);
, using the appropriate type for MyType
.
This is the problem:
template <class T>
void generate_vectorlist(const char* outfile_name = "input.txt" )
The compiler can't deduce the type of T, so it has no idea which generate_vectorlist
to use.
Call it like this:
generate_vectorlist<vectortype>(outfile_name);
Though I would actually suggest that this code doesn't make any sense in the first place.
精彩评论