为什么这段代码的输出是A类--我希望看到的是“AAA类”
#include <iostream>
using namespace std;
class A
{
public:
A(){}
virtual int Method1(int a, int b){cout << "Class A" << endl; return a+b; }
};
class AA:public A
{
public:
AA(){}
int Method1(int a, int b){cout << "Class AA" << endl; return a*b;}
};
class AAA:public A
{
public:
AAA(){}
int Method1(int a, int b){cout << "Class AAA" << endl; return a/b;}
};
class B
{
public:
B(){}
B(A a):obj(&a){}
int Method2(int a, int b){ return obj->Method1(a,b);}
private:
A *obj;
};
int main() {
A *a = new AAA();
B *b = new B(*a);
b->Method2(2,1);
return 0;
}我将新的AAA对象传递给B类并分配给*obj。这是怎么回事?诚挚的问候,
发布于 2016-07-11 18:56:25
您是传递给slicing the object构造函数的B(),所以B看到的都是A的实例,而不是AAA的实例。
仅当您通过指针/引用访问派生对象时,多态才能工作,因此可以访问虚拟方法的完整vtable。这也包括在传递派生对象时。如果通过值将派生类传递给基类变量/参数,则将对象切片,变量/参数将只能访问基类vtable项。
因此,您需要相应地更改B,要么是这样:
class B
{
public:
B() : obj(0) {} // <-- every constructor needs to initialize members!
B(A *a) : obj(a) {} // <-- accept A by pointer
int Method2(int a, int b) { return (obj) ? obj->Method1(a,b) : 0; }
private:
A *obj;
};
int main() {
A *a = new AAA();
B *b = new B(a); // <-- AAA passed by A* pointer
b->Method2(2,1);
// don't forget these
delete b;
delete a;
return 0;
}或者这个:
class B
{
public:
B() : obj(0) {} // <-- every constructor needs to initialize members!
B(A &a) : obj(&a) {} // <-- accept A by reference
int Method2(int a, int b) { return (obj) ? obj->Method1(a,b) : 0; }
private:
A *obj;
};
int main() {
A *a = new AAA();
B *b = new B(*a); // <-- AAA passed by A& reference
b->Method2(2,1);
// don't forget these
delete b;
delete a;
return 0;
}甚至这个:
class B
{
public:
// <-- note: no default constructor!
B(A &a) : obj(a) {} // <-- accept A by reference
int Method2(int a, int b) { return obj.Method1(a,b); }
private:
A &obj;
};
int main() {
A *a = new AAA();
B *b = new B(*a); // <-- AAA passed by A& reference
b->Method2(2,1);
// don't forget these
delete b;
delete a;
return 0;
}无论如何,请注意,A需要一个虚拟析构函数,因此在基类A*指针或A&引用上调用delete时,派生析构函数可以被正确调用:
class A
{
public:
...
virtual ~A() {} // <-- add this
...
};如果使用的是C++11或更高版本,则应该使用std::unique_ptr和std::shared_ptr而不是原始指针,让编译器为您处理(De)分配:
#include <memory>
class B
{
public:
B(std::shared_ptr<A> &a) : obj(a) {}
int Method2(int a, int b) { return obj->Method1(a,b); }
private:
std::shared_ptr<A> obj;
};
int main() {
std::shared_ptr<A> a(new AAA);
std::unique_ptr<B> b(new B(a));
// or: if you are using C++14 or later:
/*
std::shared_ptr<A> a = std::make_shared<AAA>();
std::unique_ptr<B> b = std::make_unique<B>(a);
*/
b->Method2(2,1);
return 0;
}https://stackoverflow.com/questions/38314170
复制相似问题