I have this class header
//header for class.
#ifndef Container_H
#define Container_H
#include <iostream>
using namespace std;
const int DEFAULT=32;
class Container{
public:
Container(int maxCapacity = DEFAULT);
~Container();
void insert(int item, int index);
void erase(int index);
int size()const;
private:
int sizeC;
int capacityC;
int * elements;
};
void info();
#endif
and this source file
#include "container.h"
Container::Container(int maxCapacity = DEFAULT){
int y;
}
void Container::insert(int item, int index){
int x;
}
and whe开发者_如何学Gon I compile this, I get the following error message
test.cpp:4: error: default argument given for parameter 1 of `Container::Container(int)'
container.h:12: error: after previous specification in `Container::Container(int)
what have I done wrong here?
Functions with no arguments still need the parentheses:
Container::Container() {
int y;
}
Based on your header, it looks like you just forgot the maxCapacity argument, and it should actually be:
Container::Container(int maxCapacity) {
int y;
}
(If you're asking about the warning too, it's pretty self-evident -- you declared an int x
but didn't do anything with it)
EDIT: Well now you've edited it to completely change the error. Now it's an error because you're specifying the default argument in both places; you're only supposed to specify it in the declaration. Leave it out in the actual implementation, like my second example above
Your Container constructor (in the source file) should be like this:
Container::Container(int maxCapacity){
// code
}
Container::Container{
int y;
}
I'm not sure what this is intended to be. If you're trying to define your ctor, it should look something like:
Container::Container(int maxCapacity) // ....
Note that you want to include the default value in the declaration, but not in the definition.
Container::Container{
int y;
}
is syntactically incorrect.
EDIT:
Try this:
Container::Container(int maxCapacity) // default argument not to be mentioned in the definition
{
int y;
}
精彩评论