gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-30 03:15:21 25 4
gpt4 key购买 nike

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

#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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com