首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > 开发语言 > C++ >

虚函数,该如何处理

2012-04-13 
虚函数#includeiostream#includecmathusing namespace stdclass Shape{virtual float printArea(){re

虚函数
#include<iostream>
#include<cmath>
using namespace std;
class Shape 
{
virtual float printArea()
{
return 0.0;
}
virtual void print();
};

class Circle:public Shape
{
public:
Circle(int r):radius(r){};
float printArea();
void print();
private:
float radius;
};

float Circle::printArea()
{
#define N 3.1415926
return N * radius * radius; 
}

void Circle::print()
{
cout<<"Radius = "<<radius<<endl;
}

class Rectangle:public Shape
{
public:
Rectangle(float l, float w):length(l), width(w){};
float printArea();
void print();
private:
float length;
float width;
};
float Rectangle::printArea()
{
return length * width;
}
void Rectangle::print()
{
cout<<"Length = "<<length<<endl;
cout<<"width = "<<width<<endl;
}
class Triangle:public Shape
{
public:
Triangle(float a, float b, float c): a1(a), b1(b), c1(c){};
float printArea();
void print();
private:
float a1;
float b1;
float c1;
};

float Triangle::printArea()
{
float s1 = (a1 + b1 + c1)/2.0;
return sqrt(s1( s1- a1) * (s1 - b1) * (s1 - c1));
}
void Triangle::print()
{
cout<<"a1 = "<<a1<<endl;
cout<<"b1 = "<<b1<<endl;
cout<<"c1 = "<<c1<<endl;
}

int main()
{
Circle a(12.0);
cout<<"Area = "<<a.printArea()<<endl;
a.print();
Rectangle b(1.0, 2.0);
cout<<"Area = "<<b.printArea()<<endl;
b.print();
Triangle c(1.0, 2.0, 3.0);
cout<<"Area = "<<c.printArea()<<endl;
c.print();
return 0;
}
这是什么问题呢?刚写的

[解决办法]
帮楼主顶顺便看下小星星。。。
[解决办法]

C/C++ code
class Shape  {    virtual float printArea()=0;    virtual void print()=0;};
[解决办法]
有什么问题吗 你的基类shape没有作用呀 如果 shape* p=new Cricle(12); 下面依次这样 然后p->print()这样就调用, 这是shape就是一个接口类也就是抽象类, shape的成员函数就 定义成纯虚函数 virtual float pritArea()=0; virtual void print(); 此时shape就不能定义对象了 如 shape sh=new shape() 就是错误的
[解决办法]
顺便说一下,三角型两边之和要大于第三边。
所以你的参数1.0,2.0,3.0无法构成三角形。
[解决办法]
float Triangle::printArea()
{
float s1 = (a1 + b1 + c1)/2.0;
return sqrt(s1( s1- a1) * (s1 - b1) * (s1 - c1));
}

这个s1有问题
[解决办法]
Compiler Error C2064
term does not evaluate to a function

A call was made to a function through an expression that did not evaluate to a function pointer.

This error is probably caused by attempting to call a nonfunction.

The following is an example of this error:

int i, j;
char* p;
void func()
{
j = i(); // error, i is not a function
p(); // error, p doesn't point to a function
}
MSDN上的解释
[解决办法]
首先看5楼
s1后面少了*
改过来后编译
出现main.obj : error LNK2001: unresolved external symbol "private: virtual void __thiscall Shape::print(void)" (?print@Shape@@EAEXXZ)



这我就不知道了

我也是初学C++
[解决办法]

探讨

首先看5楼
s1后面少了*
改过来后编译
出现main.obj : error LNK2001: unresolved external symbol "private: virtual void __thiscall Shape::print(void)" (?print@Shape@@EAEXXZ)

这我就不知道了

我也是初学C++

热点排行