Calling a Class from another class C++
I have a class path
that declares a function called
void addConnection(const book& book, const string& name)
where book
is a struct.
In my main
function I am calling a void generatePath(const string& inputName);
which isn't located in any class. When I try to call a function on the path
class, I get this compile error:
books.cpp:67: error: no matching function for call to ‘path::path()’
So my question is, how do you call a function on a class? I always thought it was:
path p;
p.addConnection(b, "f开发者_StackOverflow中文版rank");
You don't have default constructor for class path. You either want to define it or pass appropriate argument(s) to the constructor path p("i don't know what kind of arguments it expects");
Note: you don't call a class. You call a method on an instance of a class.
You don't "call" a class, you construct an object or instance of some class.
You haven't shown your code for path
, so we can only provide guesses. Mine is: You have defined a non-default constructor for path
, like
class path {
public:
path (std::string const &str) : ... {...}
// note: no "path()"
};
in which case the compiler won't synthesize that default constructor for you. Another possibility is e.g.
class path {
int &r;
};
i.e. a class where not all member variables can be default-constructed or initialized (in this case: references must be initialized), in which case the compiler can't synthesize a default constructor.
If you don't define any Constructors the default Constructor is always called and implemented when you instantiate from a class. But if you define one Constructor, the default Constructor is "away", you have then to write it yourself if you need it.
Nevertheless you should add specific more code to let us know what path is ;-)
精彩评论