在c++中创建一个赋值对象
Creating an assigning an object in c++
你好,我是c++的新手,
我可以使用Example example("123")
创建一个类的新实例
我有两个问题
-
我知道我们不能像
if(example ==NULL)
那样检查对象是否为null,因为这不是指针,我们有其他方法可以做到这一点吗。 -
我有一个返回对象的方法,比如:如何返回null?
Example get_Example() { if (example.getName().empty() { Example example("345"); return example; } return NULL // i cannot return null. }
我能做这样的事吗?
Example get_Example() {
Example example;
if (example.getName().empty() {
example = Example example("345");
return example;
}
return NULL // i cannot return null. How
}
example = Example example("345");
我知道这很愚蠢,但没有指针我怎么能做到。
-
使用指针
Example *ex = NULL
。 -
构造默认
null_example
并过载==
Example e; if (e == null_example) { e.init(); }
-
但您可以只提供一个
is_init()
函数。Example e; if (!e.is_init()) { e.init(); }
-
你的
get_example
可能类似于:void get_example(Example &e) { // method2 or method3 }
如果您可以为定义为null的对象定义一个"状态",那么检查null(或使其为null(是有意义的。
bor示例您可以定义
explicit operator bool() const
方法,并且当对象成员具有您定义的表示"非空示例"的值时返回true。
检查空Example actualexample
,此时仅为if(!actualexample)
另一个选项是使用Null对象模式。Null对象模式基本上允许yo返回一个完全构造的对象,您将其标识为Null。
链接的维基百科文章中的例子给出了一个很好的例子:
class animal
{
public:
virtual void make_sound() = 0;
};
class dog : public animal
{
void make_sound() { cout << "woof!" << endl; }
};
class null_animal : public animal
{
void make_sound() { }
};
记住,创建一个特定的"Null对象"(即在某个地方定义一个全局Example kNullExample;
(不是一个好的解决方案,因为如果你将其分配给另一个示例对象(即Example newObject = kNullExample;
(,你将无法识别该对象不再为Null的事实。
另一种选择是将布尔值存储在对象中的某个位置,并编写一个"IsNull(("函数。只有当你不能让你的类变成虚拟的(例如映射二进制文件(,或者你真的负担不起虚拟表跳转的费用时,这才是真正的解决方案。
不能以这种方式分配NULL指针,因为返回对象不是指针。如果你不想使用指针,一个可能的选项可能是使用一个特定的NULL示例对象。我的意思是用这个类的自定义属性检查对象实例是否为NULL。可以使用构造函数中传递的空字符串:
exampleNull = Example example("");
并检查字符串属性以验证您的"null"对象
但请记住:NULL只能分配给指针类型
不要生成返回值的方法,只需重写运算符==
,并在那里生成控件,因此如果执行if(example ==NULL)
,控件的重载方法将返回所需的布尔值。
- 为什么我必须在C++中添加一个赋值符号来声明一个数组
- cin >> int 给定一个字符串将 int 赋值为 0
- 复制赋值函数如何访问另一个对象的私有成员(Stroustroup 原则和实践书)?
- c++问题:给一个变量赋值后,另一个变量发生了变化
- 链表指针赋值为什么我们不能直接将尾巴分配给 temp 而不是尾巴>尾巴下一个
- 创建一个类并在C++中使用构造函数(赋值)
- 是否有必要重载具有另一个类 B 的数据成员的类 A 的赋值运算符和复制构造函数?
- 有没有办法通过从另一个文件中读取值来为宏赋值
- 在一个语句中对原子布尔变量进行多次赋值
- vector.back() 可以用来为向量的最后一个元素赋值吗?
- 为什么同时使用一个赋值运算符处理复制和移动赋值效率不高
- 在一个线程内进行的赋值在另一个线程中不可见
- 创建一个可以通过赋值初始化但不可复制的类型
- 如何使用const_reference类型来声明一个变量并为其赋值 front() 函数的返回值
- 从字符串数组打印其中一个字符串时出现空指针赋值错误
- C++返回一个数组并将其赋值给一个变量
- 正在初始化一个真正初始化的垃圾变量,或者只是一个赋值
- 在c++中创建一个赋值对象
- 输出一个赋值给c++双精度数组元素的字符串
- 为什么函数中变量的最后一个赋值不能被视为移动?