操作后通过运算符分配对象
Assigning object after operation via operator
我想添加两个类的内容并将它们保存在另一个类中。我已经创建了构造函数、参数化构造函数、析构函数和重载=
参数。它对Demo b = a;
工作正常,但是当我尝试保存a.addition(b)
给出的对象时,出现错误no viable overloaded '='
。我的概念是为什么对象没有复制到新创建的对象?
课堂演示
class Demo
{
int* ptr;
public:
Demo(int data = 0) {
this->ptr = new int(data);
}
~Demo(void) {
delete this->ptr;
}
// Copy controctor
Demo(Demo &x) {
ptr = new int;
*ptr = *(x.ptr);
}
void setData(int data) {
*(this->ptr) = data;
}
int getData() {
return *(this->ptr);
}
Demo operator = (Demo& obj) {
Demo result;
obj.setData(this->getData());
return result;
}
Demo addition(Demo& d) {
Demo result;
cout << "result: " << &result << endl;
int a = this->getData() + d.getData();
result.setData(a);
return result;
}
};
主要
int main(void)
{
Demo a(10);
Demo b = a;
Demo c;
c = a.addition(b); // error here
return 0;
}
>operator=
引用非常量(即Demo&
( 作为其参数,无法绑定到addition
返回的临时对象。
要解决此问题,您应该将参数类型更改为引用 const(即const Demo&
(,可以绑定到临时的并且是约定俗成的。
顺便说一句:任务的目标和来源似乎是相反的。我想它应该实现为
Demo& operator= (const Demo& obj) {
setData(obj.getData());
return *this;
}
并将getData
声明为const
成员函数。
相关文章:
- 使用操作重载对象重新分配对象
- 静态分配对象的值初始化
- C++ 将抽象类型的动态分配对象传递给函数并存储在向量中
- 堆分配对象中的堆栈对象在 c++ 中在哪里分配?
- 在 c++ 的构造函数中分配对象向量时出错
- 动态分配对象中的字段-动态分配更好还是静态分配更好?C++
- 操作后通过运算符分配对象
- 如何捕获源自静态分配对象的构造函数的异常?
- 在C++中,当重新分配对象时,为什么构造函数在析构函数之前触发?
- 如何使用每个对象的单个构造函数参数动态分配C++对象数组?
- 将动态分配对象传递到 boost::any 构造函数中
- 混合指向已分配对象和作用域对象的指针
- C 删除指向动态分配对象的指针
- 有关动态分配对象的问题
- 类的堆分配对象是否在其作用域之后但在 C++ 中调用其析构函数之前处于活动状态
- C++ 中的黑白堆分配对象和堆栈分配对象的性能差异
- 是隐式创建的默认构造函数,负责分配对象内存
- 如何删除用于动态分配对象的智能指针
- 分配对象数组时如何初始化每个对象
- 用于堆栈分配对象的C++虚拟析构函数内联