我有一个时间了解参考的魔鬼.请考虑以下代码:
class Animal
{
public:
virtual void makeSound() {cout << "rawr" << endl;}
};
class Dog : public Animal
{
public:
virtual void makeSound() {cout << "bark" << endl;}
};
Animal* pFunc()
{
return new Dog();
}
Animal& rFunc()
{
return *(new Dog());
}
Animal vFunc()
{
return Dog();
}
int main()
{
Animal* p = pFunc();
p->makeSound();
Animal& r1 = rFunc();
r1.makeSound();
Animal r2 = rFunc();
r2.makeSound();
Animal v = vFunc();
v.makeSound();
}
Run Code Online (Sandbox Code Playgroud)
结果是:"树皮树皮rawr rawr".
用Java的思维方式(显然已经破坏了我对C++的概念化),结果将是"树皮树皮树皮".我从前一个问题中了解到,这种差异是由切片引起的,我现在对切片的理解有了很好的理解.
但是,让我们说我想要一个返回Animal值的函数,它实际上是一个Dog. …
根据我之前的问题,我希望a boost::shared_ptr<A>实际上是A(或许是A*)的子类,以便它可以用在A*作为参数的方法中.
考虑以下课程:
class A
{
public:
A(int x) {mX = x;}
virtual void setX(int x) {mX = x;}
virtual int getX() const {return mX;}
private:
int mX;
};
Run Code Online (Sandbox Code Playgroud)
在上一个问题中,我提议创建一个SharedA对象来处理这个问题,并且可能是这样做的.
class SharedA : public A
{
public:
SharedA(A* a) : mImpl(a){}
virtual void setX(int x) {mImpl->setX(x);}
virtual int getX() const {return mImpl->getX();}
private:
boost::shared_ptr<A> mImpl;
};
Run Code Online (Sandbox Code Playgroud)
如果我可以创建一个模板类来为我处理所有这些问题,那将是Grrrrrrrrreat想的.
template <class T>
class Shared : public T
{
public:
SharedT(T* t) : mImpl(t) …Run Code Online (Sandbox Code Playgroud)