class MyStrValArray
{
private:
vector<char> p;
public:
MyStrValArray(const int n = 10, const int i = 1, const char ch = 'a')
{}
~MyStrValArray();
void init(const int n);
void clear();
unsigned capacity();
unsigned size();
char get(const int i);
void set(const char ch, const int i);
void remove(const unsigned int i);
void pushData(const char ch);
char showData();
};
This is the class I wrote. Some of the class member functions have the same parameter name, for example, ch
, i
. In this case, how can I define a constructor when the class member parameters have the same name?
+) I wanted to check whether the constructor well defined, so in the main function, I wrote p2.init()
, without any parameter. Like this:
MyStrValArray p2;
p2.init();
init
function looks like this:
void MyStrValArray::init(const int n) //Done
{
p.reserve(n);
cout << "a vector with size " << n << " created" << endl;
}
and I got this message:
error: no matching function for call to 'MyStrValArray::init()'|
I also wrote:
p2.get();
p2.set();
char MyStrValArray::get(const int i)
{
return p.at(i);
}
void MyStrValArray::set(const char ch, const int i)
{
p[i] = ch;
cout << "p[" << i << "]" << "changed to " << ch << endl;
}
And p2.get()
, p2.set()
also have the same error.
What could be the problem?
You declared and defined the init
function with an int
eger argument
class MyStrValArray
{
public:
void init(const int n);
// ...
}
void MyStrValArray::init(const int n)
// ^^^^^^^^^^^^ --> argument n
{
// ...code
}
that means the calling the function will only work with passing with an argument. You should be doing
MyStrValArray p2;
p2.init(3); // pass the `n`
If you intend to call without any arguments, you should provide a default argument to it
class MyStrValArray
{
public:
void (const int n = 3); // declaration: provide the default argument
// ^^^^^^^^^^^^^^^^
// ...
}
void MyStrValArray::init(const int n) // definition
{
// ...code
}
Now you could
MyStrValArray p2;
p2.init(); // the n = 3
"
error: no matching function for call to 'MyStrValArray::get()'|
". What could be the problem?
The above mentioned is applied for the case of MyStrValArray::get()
function too. Hence the error. Choose one of the mentioned ways to get around the problem.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.