根據您對使用新建和刪除的感受,以下內容可以實現您所要求的功能。
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
}
}
編輯:作爲Angew指出有在C++ 11管理指針的更好的方法,如果你有使用現代編譯器的選項,他的建議將導致更好看和SAF呃代碼。
來源
2014-05-15 08:18:28
rcs
使用'std :: unique_ptr'或者最好是['boost :: optional'](http://www.boost.org/doc/libs/1_55_0/libs/optional/doc/html/index.html ),會更好。 – Angew
@Angew你說得對,肯定會讓事情變得更安全。我仍然在C++ 98中陷入黑暗時代,而這些東西並不存在。我需要更好地熟悉最近的(!)開發 – rcs
'boost :: scoped_ptr'或者提到的'boost :: optional'也可以在C++ 98/03中工作。 – Angew