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();
};
这是我写的课。 一些类成员函数具有相同的参数名,例如ch,i。 在这种情况下,当类成员参数具有相同的名称时,如何定义构造函数?
+)我想检查构造函数是否定义良好,所以在main函数中我编写了p2.init(),不带任何参数。如下所示:
MyStrValArray p2;
p2.init();
init函数如下所示:
void MyStrValArray::init(const int n) //Done
{
p.reserve(n);
cout<<"a vector with size "<<n<<" created"<<endl;
}
我得到了这样一条消息:“错误:没有匹配函数用于调用'MystValArray::Init()‘”。
我还写道:
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;
}
和p2.get()
,p2.set()
也有相同的错误。
有什么问题吗?
您使用int
eger参数声明和定义了init
函数
class MyStrValArray
{
public:
void init(const int n);
// ...
}
void MyStrValArray::init(const int n)
// ^^^^^^^^^^^^ --> argument n
{
// ...code
}
这意味着调用函数只能与传递参数一起工作。 你应该
MyStrValArray p2;
p2.init(3); // pass the `n`
如果您想在不带任何参数的情况下调用,则应为其提供一个默认参数
class MyStrValArray
{
public:
void (const int n = 3); // declaration: provide the default argument
// ^^^^^^^^^^^^^^^^
// ...
}
void MyStrValArray::init(const int n) // definition
{
// ...code
}
现在你可以
MyStrValArray p2;
p2.init(); // the n = 3
“错误:调用”MystValArray::Get()“
时没有匹配的函数”。 有什么问题吗?
上述内容也适用于MyStrValArray::get()
函数的情况。 因此出现了错误。 从上面提到的方法中选择一种来解决这个问题。