[英]Returning an object in c++ by reference
我為自己設定的目標是重載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;
}
方法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;
}
我得到的錯誤是'newObj':找不到標識符。 我相信這是由於析構函數。 我試圖將類myVect
放到一個新的類中(封裝它)並構造return方法,但是它沒有改變任何東西-錯誤的類型仍然相同。 你知道如何解決這個問題嗎?
無論如何,如果是析構函數錯誤,是否意味着newObj
在返回之前newObj
被刪除了?
問題可以簡化為:
int foo()
{
if (true) // In reality, some meaningful condition
{
int x = 4;
}
return x;
}
該變量的作用域為if
塊。 它不存在。
您必須將其聲明從條件中移出,並執行該工作所需的其他任何操作……或從條件內部 return
,否則進行其他操作(引發異常?)。
例如,給出上面的演示:
int foo()
{
int x = 0; // Or some other value
if (true) // In reality, some meaningful condition
{
x = 4;
}
return x;
}
要么:
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!");
}
下一個問題將是您嘗試通過引用返回局部變量。 你不能這樣做。 而是按值返回它, 這對於您正在做的事情來說是慣用的 。
您已在一個塊內聲明了對象,因此該對象將不在外部范圍內。 通常,這將使您騰出時間來在不同分支之間重用變量名。 嘗試在語句的if
部分內創建一個newObj
,例如,注意它不會引發錯誤。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.