【发布时间】:2020-12-07 09:45:04
【问题描述】:
我不知道为什么会出现此错误。就像 a*a 将 a* 视为指针(float* 到 float* 是否与 float 到 float 相同)。显然,当我在子类中声明 a 时,问题已经解决了,但关键是我希望我的子类自动从我的父类中获得它。
当我添加“float a;”时还有一件事到程序可以运行的每个子类。所以我这样做只是为了测试它是否有效,但没有。浮点数 a 在 setA 中没有值。我刚刚添加了 cout
#include"Oblik.h"
#include<cmath>
using namespace std;
class Jednakostranicni : public GeometrijskaFigura{
float P(){
return (a*a*sqrt(3))/4; //12 13 C:\Users\Name\Desktop\prvi.cpp [Error] invalid operands of types 'float*' and 'float*' to binary 'operator*'
}
float O(){
return a+a+a; //15 12 C:\Users\Name\Desktop\prvi.cpp [Error] invalid operands of types 'float*' and 'float*' to binary 'operator+'
}
};
class Kvadrat : public GeometrijskaFigura{
float P(){
return a*a;//23 12 C:\Users\Name\Desktop\prvi.cpp [Error] invalid operands of types 'float*' and 'float*' to binary 'operator*'
}
float O(){
return a+a+a+a;//26 12 C:\Users\Name\Desktop\prvi.cpp [Error] invalid operands of types 'float*' and 'float*' to binary 'operator+'
}
};
class Krug : public GeometrijskaFigura{
float P(){
return a*a*3.14;//34 12 C:\Users\Name\Desktop\prvi.cpp [Error] invalid operands of types 'float*' and 'float*' to binary 'operator*'
}
float O(){
return 2*a*3.14;//37 12 C:\Users\Name\Desktop\prvi.cpp [Error] invalid operands of types 'int' and 'float*' to binary 'operator*'
}
};
int main(){
GeometrijskaFigura *f;
int x;
cin>>x;
f->setA(x);
f=new Jednakostranicni;
cout<<"Jednakostranicni-P: "<<f->P()<<" O: "<<f->O()<<endl;
f=new Kvadrat;
cout<<"Kvadrat-P: "<<f->P()<<" O: "<<f->O()<<endl;
f=new Krug;
cout<<"Krug-P: "<<f->P()<<" O: "<<f->O()<<endl;
return 1;
}
// this is Oblik.h file code
#include<iostream>
using namespace std;
class GeometrijskaFigura{
protected: float a;
public:
void setA(float b){
a=b;
}
virtual float P()=0;
virtual float O()=0;
};
【问题讨论】:
-
不要在标题中使用
using namespace std;! Why is “using namespace std;” considered bad practice? -
无法复制:godbolt.org/z/nf35P3
-
请确保您发布的代码是有错误的代码,并在问题中包含完整的错误消息。另见minimal reproducible example
-
... 并通过注释识别导致错误的行(此处的行号很棘手)。