#include <iostream>
#include <math.h>
using namespace std;
class circle
{
public:
float l,s,d;
void set();
void display();
private:
float r;
}cir1,cir2;
int main(int argc, char** argv) {
cir1.set();
cir1.display();
cir2.set();
cir2.display();
return 0;
}
void circle::set()
{
float r,l,s,d;
cout<<"Please input the radius:"<<endl;
cin>>r;
l=3.1415926*r*2;
s=r*r*3.1415926;
d=2*r;
}
void circle::display()
{
cout<<"The radius is: "<<r<<endl;
cout<<"The area is: "<<s<<endl;
cout<<"The diameter is: "<<d<<endl;
cout<<"The circumference is: "<<l<<endl;
}
是想用类输入半径求圆面积,直径,周长,运行不报错但是结果是错的是为什么?
把 set 函数里的 局部变量 定义 去掉就对了
float r,l,s,d;
这个语句,把类中的同名成员变量给隐藏了,赋值给了局部变量。去掉这句话就对了。
仍然和构造函数一样:编译器生成默认的析构函数会对自定义类型成员调用它的默认析构函数(内置类型成员,销毁时不需要资源清理,最后系统直接将其内存回收即可)
class Stack
{
public:
// Init
// Destroy
Stack(int capacity = 10)
{
_a = (int*)malloc(sizeof(int)*capacity);
assert(_a);
_top = 0;
_capacity = capacity;
}
~Stack()
{
cout << "~Stack():" << this << endl;
free(_a);
_a = nullptr;
_top = _capacity = 0;
}
private:
int* _a;
int _top;
int _capacity;
};
class Date
{
public:
Date(int year = 1, int month = 1, int day = 1)
{
_year = year;
_month = month;
_day = day;
}
void Print()
{
cout << _year << "-" << _month << "-" << _day << endl;
}
//~Date()
//{
// cout << "~Date()" << endl;
//}
private:
int _year; // 年
int _month; // 月
int _day; // 日
};
int main()
{
Stack st1(1);
Stack st2(2);
return 0;
}