重载用于指向两个不同类的指针的赋值运算符 [英] Overloading assignment operator for pointers to two different classes

查看:279
本文介绍了重载用于指向两个不同类的指针的赋值运算符的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的问题:
我试图重载的赋值运算符指向两个不同的类的指针。以下是一个示例:

My Question: I'm trying to overload the assignment operator for pointers to two different classes. Here is an example:

dc.h:

#ifndef DC_H_
#define DC_H_

#include "ic.h"

class dc {

double d;
char c;

public:

dc(): d(0), c(0) { }

dc(double d_, char c_): d(d_), c(c_) { }

dc* operator=(const ic* rhs);

~dc() { }

};

#endif /* DC_H_ */

class ic.h:

class ic.h:

#ifndef IC_H_
#define IC_H_

class ic {

int i;
char c;

public:

ic(): i(0), c(0) { }

ic(int i_, char c_): i(i_), c(c_) { }

~ic() { }

};

#endif /* IC_H_ */

dc.cpp:

#include "dc.h"

dc* dc::operator=(const ic* rhs) {
d = rhs->i;
c = rhs->c;  
return this;
}

ic.cpp:

#include "ic.h"

cpp:

#include "dc.h"
#include "ic.h"

#include<iostream>

int main() {

dc DC;
ic IC;

dc* dcptr = &DC;
ic* icptr = &IC;

dcptr = icptr;

return 0;
}

我收到以下错误信息:


错误:无法在作业

error: cannot convert 'ic*' to 'dc*' in assignment

所有这些工作,如果我用引用而不是指针。不幸的是,因为我想使用指针ic和dc作为另一个类中的成员,我不能使用引用,因为引用作为成员必须初始化,一旦初始化,它们不能改变为引用另一个对象。我想用ic和dc进行算术运算,例如:

All this works if I do it with references instead of pointers. Unfortunately since I would like to use pointers to ic and dc as members in another class I cannot use references since references as members have to be initialized and once initialized they cannot be changed to refer to another object. I'd like to be able to make arithmetic operations with ic and dc e.g.:

dc *d1, *d2, *d3;
ic *i1, *i2, *i3;
*d1 = (*d1)*(*i1) + (*i2)*(*d2) - (*d3)*(*i3);



< (*)*(*)。而是类似这样的:

d1 = d1*i1 + i2*d2 - d3*i3;

这就是为什么我想这样做的原因。请让我知道,如果这是可能的。对我来说,似乎编译器想要调用默认指针,而不是重载的指针。

This is the reason why I'd like to do this. Please let me know if this is possible at all. To me it seems that the compiler wants to call the default pointer to pointer assignment instead of the overloaded one.

感谢您的帮助!

推荐答案

指针的运算符。

一个选项,如果你想坚持运算符重载是一个指针包装器对象,一个对象包含一个指向对象的指针 - 本质上是一个智能指针,重载该对象的操作符。

One option, if you want to stick with operator overloading is to make a pointer wrapper object, an object that contains a pointer to the object - essentially a smart pointer, and overload the operators of that object.

这篇关于重载用于指向两个不同类的指针的赋值运算符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆