简体   繁体   中英

Error: no appropriate default constructor available

Even i have tried a lot but i don't know where's error in my code. It seems just so easy.

enum Suit { none, clubs, diamonds, hearts, spades };
enum Symbol { none_, ace, king, queen, jack, ten, nine, eight, seven };

class Card
{
private:
    Suit suit_;
    Symbol symbol_;

public:

    Card(Suit suit, Symbol symbol)
    {
        suit_=suit;
        symbol_=symbol;
    };

Your class does not have a default constructor . It is not a problem in itself. However, if you try to call the non-exist default constructor the error will be shown. You probably doing something like this in other place (one of those lines is enough to throw that error):

Card x;
std::vector<Card> v(3);
auto x=std::make_shared<Card>();
//...and many others...

Solution?

If you really do not want that the Card being allocated without giving argument, you should not do this. Find the code that trying to allocate a Card object and alter it. BTW it is preferred to delete the default constructor in a clear statement like this:

class Card{
private:
    Suit suit_;
    Symbol symbol_;
public:
    Card()=delete;
    Card(Suit suit, Symbol symbol)
    {
        suit_=suit;
        symbol_=symbol;
    }
};

If you are OK with allocating objects from Card class with default values then add this instead:

class Card{
private:
    Suit suit_;
    Symbol symbol_;
public:
    Card()=default;
    //Or Card():suit_(some_value),symbol_(somevalue){}
    Card(Suit suit, Symbol symbol)
    {
        suit_=suit;
        symbol_=symbol;
    }
};

You have defined your own constructor, under such cases, the compiler does not add the default constructor. Henceforth, if you are trying to create an object as mentioned below, you will end up with no default constructor error

card obj; // Error

solution:

1) pass the arguments, while creating the object ( Most appropriate as per the snippet):

example:

Suit suitenum = clubs;  
Symbol symnum = king;
Card obj(suitenum,symnum);

2) Define a default constructor:

class Card
{
    private:
        Suit suit_;
        Symbol symbol_;

    public:
        Card(){};

        Card(Suit suit, Symbol symbol)
        {
            suit_=suit;
            symbol_=symbol;
        };

};  

To cut it short and simple you just have to provide default constructor (no arguments).

Card()
{
}

The reason you require default constructor is you are using vector (container) of this type. (class). and for container classes, the contained class (card) must have the default constructor.

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM