[英]Returning a class type in C++
很抱歉再次詢問,
但我試圖解決這個錯誤有一陣子:
#include <iostream>
using namespace std;
class time{
private:
int m;
int h;
public:
time():m(0),h(0) {};
time(int x,int y): m(x),h(y) {}
int getm() const {return this->m;}
int geth() const {return this->h;}
void print() const;
time operator+(time aa);
time operator-(const time &a) const;
};
void time::print() const
{
cout <<"Hour: "<<h<<endl<<"Mins: "<<m<<endl;
}
time time::operator+( time &a)
{
time temp;
temp.m= this->m+a.getm();
temp.h=this->h+a.geth();
return temp;
}
int main ()
{
return 0;
}
我收到一條錯誤消息,指出時間未命名類型,我不太確定該錯誤,它應該可以工作。
也關於指針
給定我有一個雙指針指向一個指針,該指針指向動態數據。
int *ptr=new int
int **p=&ptr;
delete p;
因此將刪除p,首先刪除動態數據,然后刪除指針ptr?
問題是“時間”是C標准庫中的函數,請參見此處 。 嘗試給班級命名。
您需要更正方法聲明或定義。
|----- Remove reference operator
V
time time::operator+( time &a)
{
time temp;
temp.m= this->m+a.getm();
temp.h=this->h+a.geth();
return temp;
}
關於第二個問題
給定我有一個雙指針指向一個指針,該指針指向動態數據。
int *ptr=new int;
int **p=&ptr;
delete p;
那么將
delete p
,首先刪除動態數據,然后刪除指針ptr
?
沒有! 而且,您根本不應刪除p
,因為它不是使用new
創建的。
規則很簡單, new
和delete
成對出現。 如果您使用new
創建某些內容,則應使用delete
銷毀它(並且僅銷毀一次)。
在您的情況下,正確的方法是delete ptr
使用new創建的delete ptr
。 作為一個稍微令人困惑的選項,您可以改為使用delete *p
,因為p
指向ptr
。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.