不使用构造函数的c++类声明

C++ Class Declaration without using its Constructor

本文关键字:c++ 声明 构造函数      更新时间:2023-10-16

我遇到过几次这种情况,最后我删除了初始构造函数。我在谷歌上搜索过,但我甚至不知道这叫什么…

class you {
    private:
        string name;
        int number; 
        COLORREF color;   
        drinks favoriteDrink;  // here
    public:
        you(string Name, int Number, COLORREF Color);
        string GetName();
        int GetNumber();
        COLORREF GetColor();
};

Drinks是另一个类,它的构造函数看起来像:(int x, bool y),我想进一步初始化它。同样,通常我只是删除构造函数并编写一个函数ex: init(w/e)。有办法做到这一点吗?

定义构造函数时,它可以包含成员初始化列表。这是初始化成员和基类的正确方法。所以你可以这样实现you的构造函数:

you::you(string Name, int Number, COLORREF Color) :
  name(Name),
  number(Number),
  color(Color),
  drink(whatever_arguments, you_want)
{
  // body as usual
}

注意,这是初始化类数据成员的惟一方式。如果你这样做:
you::you(string Name, int Number, COLORREF Color)
{
  name = Name;
  number = Number;
  color = Color;
}

则不是初始化成员,而是赋值给它们。空成员初始化列表将首先默认初始化它们。这意味着调用类的默认构造函数,并为基本类型留下未初始化的值。然后,构造函数体通过赋值来覆盖它们。

最好使用成员初始化器列表,因为这样可以跳过(无用的)默认初始化。有时,如果您有一个不可赋值的成员(如const成员、引用或仅仅是一个没有可访问赋值操作符的对象),这也是唯一的方法。

根据您对使用new和delete的感觉,以下操作可以实现您的要求。

Angew的方法是最好的方法,如果你知道x和y的值足够早,如果你需要构造favoriteDrink以后,你可以考虑如下:

class drinks; // Forward declare class rather than #including it    
class you 
{    
private:
    string name;
    int number; 
    COLORREF color;   
    drinks* favoriteDrink;  // Constructor will not be called
public:
    you(string Name, int Number, COLORREF Color);
    ~you();
    void someFunction(void);
    string GetName();
    int GetNumber();
    COLORREF GetColor();    
};

然后在实现中:

#include "drinks.h" // Include it now we need it's implementation
you::you(string Name, int Number, COLORREF Color) :
  name(Name),
  number(Number),
  color(Color),
  favoriteDrink(NULL) // Important to ensure this pointer is initialised to null
{
  // body as usual
}
you::~you()
{
   delete favoriteDrink; // Ok to delete even if it was never newed, because we initialised it to NULL
   favoriteDrink = NULL; // Always set your pointer to null after delete
}
void you::someFunction(void)
{
   favoriteDrink = new drinks(3, 6) // Then once you know your values for x and y
   // Always check if the pointer is null before using
   if (favoriteDrink)
   {
      // Use the pointer
   }
}

Edit:正如Angew指出的,在c++ 11中有更好的方法来管理指针,如果你有使用现代编译器的选择,他的建议将导致更美观和更安全的代码。