zor*_*o47 0 c++ operator-overloading
我为自己设定的目标是重载operator+(添加类对象)。事实证明,该总和可以解释为两个向量的总和。但是当涉及到该方法时operator+,我发现很难返回该对象。我读过类似的主题,甚至尝试应用一些建议,但不幸的是没有成功。我附上一些代码。
template<class Y>
class myVect {
public:
myVect(int n = 1);
~myVect();
myVect(const myVect& a);
myVect& operator= (const myVect&);
myVect& operator+ (const myVect&);
void display(const myVect& a);
private:
int size;
Y* data;
template<class U> friend class myClass;
};
template<class Y> // constructor
myVect<Y>::myVect(int n) {
size = n;
data = new Y[size];
cout << endl << "Pass the elements" << " " << size << "\n";
for (int i = 0; i < size; i++) {
cin >> *(data + i);
}
}
template <class Y> // deconstructor
myVect<Y> :: ~myVect() {
delete[] data;
}
template<class Y> // copy constructor
myVect<Y> ::myVect(const myVect & a) {
size = a.size;
data = new Y[size];
for (int i = 0; i < size; i++) {
*(data + i) = *(a.data + i);
}
}
template<class Y> //ASSIGMENT OPERATOR
myVect<Y> & myVect<Y> :: operator= (const myVect<Y> & a) {
if (this != &a) {
delete[] data;
size = a.size;
data = new Y[size];
for (int i = 0; i < size; i++) {
*(data + i) = *(a.data + i);
}
}
return *this;
}
Run Code Online (Sandbox Code Playgroud)
方法operator +如下:
template<class Y>
myVect<Y>& myVect<Y> ::operator+ (const myVect<Y>& a) {
if (this->size != a.size) {
cout << endl << "not able to perform that operation - wrong dimensions" << endl;
}
else {
myVect<Y> newObj(this->size);
for (int i = 0; i < this->size; i++) {
*(newObj.data + i) = *(this->data + i) + *(a.data + i);
}
}
return newObj;
}
Run Code Online (Sandbox Code Playgroud)
我得到的错误是'newObj':找不到标识符。我相信这是由于析构函数。我试图将类myVect放入一个新类中(封装它)并构造return方法,但它没有改变任何东西-错误的类型仍然相同。你知道如何解决这个问题吗?
无论如何,如果这是析构函数错误,是否意味着它newObj在返回之前就被删除了?
问题可以简化为:
int foo()
{
if (true) // In reality, some meaningful condition
{
int x = 4;
}
return x;
}
Run Code Online (Sandbox Code Playgroud)
该变量的作用域为if块。它不存在。
您必须将其声明从条件中移出,并执行该工作所需的其他任何操作……或return从条件内部进行,否则进行其他操作(引发异常?)。
例如,给出上面的演示:
int foo()
{
int x = 0; // Or some other value
if (true) // In reality, some meaningful condition
{
x = 4;
}
return x;
}
Run Code Online (Sandbox Code Playgroud)
要么:
int foo()
{
if (true) // In reality, some meaningful condition
{
int x = 4;
return x;
}
throw std::runtime_error("For some reason I have no value to give you!");
}
Run Code Online (Sandbox Code Playgroud)
下一个问题将是您尝试通过引用返回局部变量。你不能这样做。而是按值返回它,这对于您正在做的事情来说是惯用的。
| 归档时间: |
|
| 查看次数: |
88 次 |
| 最近记录: |