如何将对象中的某个值赋给长变量
How do I assign a certain value from an object to a long variable?
示例:
long a;
BoundedCounter e;
所以我想把类中私有变量计数器的值分配给
a=e;
尝试使用此:
long int & operator=(long b)
{
b=counter;
return b;
}
和
long int & operator=(long b, BoundedCounter &a)
{
b=a.getCounter();
return b;
}
返回编译错误:
无法在分配中转换
BoundedCounter' to
long int
和
`long int&operator=(long int,BoundedCounter&('必须是非静态成员函数
当左边是普通变量而不是对象时,我如何在类之外定义一个运算符=?
operator=
在这里不合适,因为赋值的左侧是基元类型(不能为基元类型定义operator=
(。尝试给BoundedCounter
一个operator long
,例如:
class BoundedCounter
{
public:
// ...
operator long() const
{
return counter;
// or return getCounter();
}
};
您的代码正在从BoundedCounter
转换为long
,因此您需要定义一个从BoundedCounter
到long
:的转换(强制转换(运算符
class BoundedCounter {
private:
long a_long_number;
public:
operator long() const {
return a_long_number;
}
};
您定义的赋值运算符将允许您将long
值分配给BoundedCounter
类的实例,这与您尝试执行的操作相反。
相关文章:
- 你能重载对象变量名本身返回的内容吗
- 将包含C样式数组的对象初始化为成员变量(C++)
- 将地址分配给本地指针后,公共对象的变量将消失
- 为什么我们再次从结构对象创建结构变量?
- 如何在初始化列表中的构造函数之后初始化变量/对象?
- 从变量对象指向基对象
- C++ - 我可以创建编译时变量对象吗?
- 动态数组添加元素而不创建结构变量/对象
- Visual Studio C++ 编译器在局部变量对象上的奇怪行为
- 其中定义函数的静态局部变量对象
- QT良好的全局变量/对象处理
- r 值的匿名变量对象与真实对象
- QT 测试 - 变量/对象失去价值
- 访问私有变量对象
- C++访问具有相同名称的变量/对象的命名空间中的全局变量/对象
- C++-访问全局变量对象
- 表达式必须具有类类型:c++,将实例变量对象作为指针传递(点表示法参数)
- C++变量/对象和堆内存管理
- 如何在每次迭代中创建一个新变量/对象的循环
- 初始化现有变量/对象的新构造函数