C++ 虚函数未解析为大多数派生类方法 #包括 使用名称空间std; 类形木 { 公众: 虚拟整数get_x(int); 受保护的: int x; }; 广场类:公共形木 { 公众: 无效集_x(int,int); int-get_x(int); 私人: int x_坐标[3]; int y_坐标[3]; }; int main() { 正方形*s=新正方形; s->set_x(0,20); 在这些行中,cout
:C++ 虚函数未解析为大多数派生类方法 #包括 使用名称空间std; 类形木 { 公众: 虚拟整数get_x(int); 受保护的: int x; }; 广场类:公共形木 { 公众: 无效集_x(int,int); int-get_x(int); 私人: int x_坐标[3]; int y_坐标[3]; }; int main() { 正方形*s=新正方形; s->set_x(0,20); 在这些行中,cout,c++,debugging,object,polymorphism,C++,Debugging,Object,Polymorphism,: #include <iostream> using namespace std; class ShapeTwoD { public: virtual int get_x(int); protected: int x; }; class Square:public ShapeTwoD { public: void set_x(int,int); int get_x(int);
#include <iostream>
using namespace std;
class ShapeTwoD
{
public:
virtual int get_x(int);
protected:
int x;
};
class Square:public ShapeTwoD
{
public:
void set_x(int,int);
int get_x(int);
private:
int x_coordinate[3];
int y_coordinate[3];
};
int main()
{
Square* s = new Square;
s->set_x(0,20);
cout<<s->get_x(0)
<<endl;
ShapeTwoD shape[100];
shape[0] = *s;
cout<<shape->get_x(0); //outputs 100 , it doesn't resolve to
// most derived function and output 20 also
}
void Square::set_x(int verticenum,int value)
{
x_coordinate[verticenum] = value;
}
int Square::get_x(int verticenum)
{
return this->x_coordinate[verticenum];
}
int ShapeTwoD::get_x(int verticenum)
{
return 100;
}
您有“切片”。您的shape
数组包含shapewod
s,您可以从*s
分配给第一个shapewod
。这不会更改shape[0]
的类型,因此它不是Square
类型的对象。多态性只能在使用指针时起作用:
ShapeTwoD shape[100];
shape[0] = *s;
shapewod*shape[100];//现在有100个(未初始化)指针
形状[0]=s;
得不到x(0);
在这些行中:
#include <iostream>
using namespace std;
class ShapeTwoD
{
public:
virtual int get_x(int);
protected:
int x;
};
class Square:public ShapeTwoD
{
public:
void set_x(int,int);
int get_x(int);
private:
int x_coordinate[3];
int y_coordinate[3];
};
int main()
{
Square* s = new Square;
s->set_x(0,20);
cout<<s->get_x(0)
<<endl;
ShapeTwoD shape[100];
shape[0] = *s;
cout<<shape->get_x(0); //outputs 100 , it doesn't resolve to
// most derived function and output 20 also
}
void Square::set_x(int verticenum,int value)
{
x_coordinate[verticenum] = value;
}
int Square::get_x(int verticenum)
{
return this->x_coordinate[verticenum];
}
int ShapeTwoD::get_x(int verticenum)
{
return 100;
}
您有“切片”。您的shape
数组包含shapewod
s,您可以从*s
分配给第一个shapewod
。这不会更改shape[0]
的类型,因此它不是Square
类型的对象。多态性只能在使用指针时起作用:
ShapeTwoD shape[100];
shape[0] = *s;
shapewod*shape[100];//现在有100个(未初始化)指针
形状[0]=s;
得不到x(0);
你有一个ShapeTwoD
数组,而不是Square
数组。查找“对象切片”。可能重复的是ShapeTwoD
数组,而不是Square
数组。查找“对象切片”。可能重复的感谢,感谢你的帮助谢谢,感谢你的帮助