在C++中返回类类型
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 *p
,因为p
指向ptr
。
相关文章:
- 如何在模板参数中分离函数类型返回类型和参数
- 为什么要为指针返回类型返回一系列字符?
- 有没有办法根据运行时值的类型返回 constexpr 对象
- 从弱指针返回类型返回共享指针
- 无法为unique_ptr返回类型返回 nullptr
- 为什么双重类型返回无穷大
- std::is_arithmetic 为通用 lambda 中的 int 类型返回 false:未定义的行为?
- C 策略设计具有可变类型返回值
- 根据类型返回一个值
- 在C++中,将double转换为long的类型返回了不正确的值
- 作为宏参数的安装类型返回错误:字符串常量之前的预期非限定 id
- 具有引用类型返回的函数
- C++ 如何使模板<T>f() 为整数 T 返回 -1,为指针类型返回 nullptr
- C++模板:按类型返回值
- 以Integer返回类型返回浮点值
- 使用 C++14 的自动功能类型返回扣除代替 std::common_type 是否始终安全?
- 为什么允许新运算符向每个指针类型返回*void
- 适当的函数返回类型返回日期时间
- c++中布尔类型返回函数的默认返回值
- 在c#中使用非托管c++代码对所有double类型返回0