C++面向对象编程时类中const的使用

代码纠错:

今天在用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;
			...
};
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 2
    评论
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值