c++请高手帮忙指教一下这个程序的疑问,谢谢。
来源:百度知道 编辑:UC知道 时间:2024/06/04 18:47:42
#include <iostream>
#include <math.h>
using namespace std;
class Shape {
public:
virtual void draw()const=0;这里的void不就是说明无返回类型嘛,我如果在这里不写void为什么就通不过啊?最重要的是,我如果在这里不用纯虚函数,而是virtual void draw() const{}这样为什么不可以呢?
virtual ~Shape() { }
};
class Point : public Shape {
public:
Point(double x, double y) :
x_(x), y_(y)
{ }
virtual void draw() const;
double distance(const Point &pt) const
{
return sqrt((x_ - pt.x_)*(x_ - pt.x_) + (y_ - pt.y_)*(y_ - pt.y_)) ;
}
private:
double x_,y_;
};
void Point::draw() const
{
cout << '(' << x_<<','<<y_ << ')' << endl;
}
int main()
{
Point* pt1 = new Point(3, 0);
Point* pt2 = new Point(0, 4);
Shape* s = pt1;
s->draw();
s = pt2;
s->dr
#include <math.h>
using namespace std;
class Shape {
public:
virtual void draw()const=0;这里的void不就是说明无返回类型嘛,我如果在这里不写void为什么就通不过啊?最重要的是,我如果在这里不用纯虚函数,而是virtual void draw() const{}这样为什么不可以呢?
virtual ~Shape() { }
};
class Point : public Shape {
public:
Point(double x, double y) :
x_(x), y_(y)
{ }
virtual void draw() const;
double distance(const Point &pt) const
{
return sqrt((x_ - pt.x_)*(x_ - pt.x_) + (y_ - pt.y_)*(y_ - pt.y_)) ;
}
private:
double x_,y_;
};
void Point::draw() const
{
cout << '(' << x_<<','<<y_ << ')' << endl;
}
int main()
{
Point* pt1 = new Point(3, 0);
Point* pt2 = new Point(0, 4);
Shape* s = pt1;
s->draw();
s = pt2;
s->dr
virtual void draw()const=0;这里的void不就是说明无返回类型嘛,我如果在这里不写void为什么就通不过啊?最重要的是,我如果在这里不用纯虚函数,而是virtual void draw() const{}这样为什么不可以呢?
无返回类型也必须要写void(这个是普通的格式,纯虚函数就像普通函数一样,必须要写void,就像你编写函数,写void draw(){/*...*/}还是写draw(){/*...*/}呢?还有,纯虚函数ok,你要写virtual,就等于你承认这是虚函数了,那你这个后面的const?纯虚函数的格式就是virtual 类型 函数名()const=0)还有你这里定义了函数体,那么派生类怎么办?
无返回类型一定要void,不写一般默认返回int类型
virtual void draw() const{}这样可以啊。我这编译通过。
你得到的错误可能是C++函数默认不是int型返回值,这是C++支持ISO98后改的。以前在C中可以默认返回值类型是int.
也就是说,现在如果你的函数没有返回值,就需要用void.