c++ - 指向第二个基础对象的指针

标签 c++ oop

我在书中读到,如果将基指针指向派生对象然后递增指针,它不会指向下一个派生对象。它将指向下一个基础对象。但是怎么办?我尝试了以下内容:

#include <iostream>
using namespace std;


class Base{
    int x;
    public:
        void setx(int x){
            this->x = x;
        }
        int getx(){
            return x;
        }
};

class Derived : public Base{
    int y;
    public:
        void sety(int y){
            this->y = y;
        }

        int gety(){
            return y;
        }
};


int main()
{
Base *p;// pointer to base type

Base base_object; // object of base
Derived derived_object;
Base secondBaseObj;


//use p to access the base object

p = &base_object;
p->setx(10);
cout << "Base object value of x: "<< p->getx()<<endl;
base_object.setx(100);
cout << "Base object value of x: "<< p->getx()<<endl;

p->setx(20);
cout << "Base object value of x: "<< base_object.getx()<<endl;




p = &derived_object;
derived_object.sety(15);
//cout << "Derived object value of y: "<< p->gety()<<endl;
//although base pointer can be used to point a derived object, you can access only those members
// of the derived object that are inherited from the base class;


p = p+1;
secondBaseObj.setx(30);
cout << "SecBase object value of x: "<< p->getx()<<endl;

return 0;
}

输出:

Base object value of x:10
Base object value of x:100
Base object value of x:20
SecBase object value of x:15

我将指针增加 1 并调用了 gex() 函数,但它返回了派生类 gety() 函数的值。

最佳答案

您可能误解了这本书。递增指针背后的想法是,当对象是连续的时,递增指针将使指针指向下一个对象。

但是什么时候对象是连续的?一般规则是两个对象不连续,除非标准另有规定。这些情况相当有限:普通数组 T[N] , std::vector<T> , std::array<T,N> , std::basic_string<Ch> , std::valarray<T> (有资格),和std::complex<T> .

在所有这些情况下,T对象是连续的,但它们的基数不是。

关于c++ - 指向第二个基础对象的指针,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57108000/

相关文章:

c++ - 回车在 xcode 控制台 c++ 中不起作用

c++ - 为什么会有函数隐式转换为 boolean 值?

python - 为什么函数标签在该函数的范围内,但类方法标签不在其自身范围内?

c++ - 无效使用不完整类型 'PGconn {aka struct pg_conn}'

php - 如何让用户为不同的事件连续创建相同的 HTML 表单?

c++ - 在qt进程之间传递参数?

c++ - 在 C 或 C++ 中,有没有办法在没有继承的情况下扩展类?

c++ - 如何覆盖 Windows 键盘快捷键?

c# - 我应该将费用/折扣列表合并到订单类别中还是让它们成为项目行

css - 可重用性概念可以应用于 css 吗?