问题
I have the following class:
class Tileset { //base class
public:
static std::vector<Tileset*> list;
virtual ~Tileset() = 0;
protected:
std::vector<Tile> tiles_list;
sf::Texture sheet;
private: //non copiable
Tileset(const Tileset&);
Tileset& operator=(const Tileset&);
};
where sf::Texture
has a default constructor
From my understanding a default constructor should be generated since every member can be default-constructed too.
Yet I have a compiler error when I try to construct a derived object without calling a Tileset
constructor.
Can someone explain why no default constructor is generated?
edit : forgot to mention that Tile
class doesn't have a default constructor. I'm not sure if that changes anything
回答1:
A default constructor will be not be generated if any of the following are true
- There is a user defined constructor declared
- The type has a
const
or reference field
You declared a constructor hence C++ won't provide a default generated one. In this case though all of the fields of Tileset
have useful default constructors so defining a default constructor here is very easy
Tileset() { }
回答2:
When you don't provide any constructor, only then the compiler generates the default constructor for your class. If you provide a constructor (even copy-constructor), then compiler will not generate the default constructor.
By "provide" I mean when you declare and "optionally" define a constructor in your class.
回答3:
From C++ spec, 12.1.5
If there is no user-declared constructor for class X, a default constructor is implicitly declared. An implicitly-declared default constructor is an
inline public
member of its class.
Your Tileset
class declared a constructor, hence C++ compiler did not declare an implicit constructor for you. The rationale for this behavior is that since you provided constructors that take parameters, you probably need these parameters in order to properly initialize an instance of your class. The assumption here is that if you wanted a default constructor in addition to a non-default one, you'd simply declare it.
来源:https://stackoverflow.com/questions/10638527/at-what-condition-is-the-default-constructor-generated