不使用构造函数的c++类声明
C++ Class Declaration without using its Constructor
我遇到过几次这种情况,最后我删除了初始构造函数。我在谷歌上搜索过,但我甚至不知道这叫什么…
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中有更好的方法来管理指针,如果你有使用现代编译器的选择,他的建议将导致更美观和更安全的代码。
相关文章:
- .cpp和.h文件中的模板专用化声明
- 未在作用域中声明unordered_map
- C++避免重复声明的语法是什么
- 如何确保C++函数在定义之前声明(如override关键字)
- 错误:未在此范围内声明'reverse'
- 奇怪的(对我来说)返回声明 - 在谷歌上找不到任何关于它的信息
- 为什么在定义函数之前先声明它
- 如何声明特征矩阵,然后通过嵌套循环初始化它
- #ifdef和未声明的标识符
- 没有显式声明的int[]中的foreach
- 在基于范围的for循环中使用结构化绑定声明
- 在将变量声明为引用时,堆在释放后使用
- C++:无法访问声明的受保护成员
- 为什么我不能在一个类的不同行中声明和定义成员变量?
- 我不明白为什么我声明一个空的内部结构并将其传递给构造函数
- 使用cmake从源代码构建MySQL连接器/C++失败(与以前的声明冲突)
- 在函数内部的声明中初始化数组,并在外部使用它
- Visual Studio中的函数声明和函数定义问题
- c++类声明时,相同的例程,不同的成员变量类型
- 在 .h 文件中的类中声明静态变量和在.cpp文件中声明"global"变量有什么区别