代码纠错:
今天在用c++写面向对象程序设计,其中写到了类的继承,用到了复制构造函数,就一直报错,原因是在派生类中复制构造函数用const修饰,但是在派生类(默认为public继承)中不能使用相应的函数(普通)访问基类的私有属性,要想访问必须将函数定义为常量函数(const)
问题描述:
报错提示:‘this’ argument to member function ‘getx’ has type ‘const Point’, but function is not marked const
主要代码如下:
class Point {
private:
...
public:
double getx() {
return x;
}
double gety() {
return y;
...
};
class Point3d: public Point {
double dist(const Point &p) {
return (sqrt((getx() - p.getx()) * (getx() - p.getx()) + (gety() - p.gety()) * (gety() - p.gety()) + (z - getz()) *
(z - getz())));
};
原因分析:
成员函数“getx”的“this”参数的类型为“const Point”,但函数未标记为const
解决方案:
将相关的成员函数定义为const函数
如下:
class Point {
private:
...
public:
double getx()const {//定义为const函数
return x;
}
double gety()const {
return y;
...
};