-2

我正在用 C++ 编写一个库,并且想知道使用引用和/或指针代替接口(即使用(抽象)基类作为派生类的占位符)。

问题是,我应该选择两者中的哪一个?我应该更喜欢一个吗?使用对(抽象)基类的引用而不是指针有什么区别吗?

请查看以下代码摘录,并对任何问题发表评论:

#include <iostream>

class Base {
    protected:
    public:
        virtual void Print() const {
            std::cout << "Base" << std::endl;
        }
};

class Derived : public Base {
    protected:
    public:
        void Print() const override {
            std::cout << "Derived" << std::endl;
        }
};

class AnotherDerived : public Base {
    protected:
    public:
        void Print() const override {
            std::cout << "Another Derived" << std::endl;
        }
};

void someFunc( const Base& obj ) {
    obj.Print();
}

void anotherFunc( const Base* obj ) {
    obj->Print();
}

int main( int argc, char* argv[] ) {
    Base baseObj, *basePtr;
    Derived derivedObj;
    AnotherDerived anotherDerivedObj;

    someFunc( derivedObj );
    anotherFunc( &derivedObj );
    someFunc( anotherDerivedObj );

    /* slicing ??? */
    baseObj = derivedObj;
    /* another slicing ??? */
    baseObj = anotherDerivedObj;

    /* proper use */
    basePtr = &anotherDerivedObj;

    someFunc( baseObj );
    anotherFunc( basePtr );

    return 0;
}

我想,在上面的代码中,我在将子对象复制分配给父对象时进行对象切片。但是,假设我没有做任何对象切片(如前两次调用someFunc),参考方法会做我打算做的事情吗?dynamic_cast在决定调用哪个多态函数时,引用和指针方法是否都在内部使用?或者,我完全错过了这里的重点吗?

在此先感谢您的时间!

4

1 回答 1

1

对于函数和方法参数,我的经验法则是使用常量引用 ( const &) 来仅输入必需的参数。使用 aconst *作为输入参数,也可以使用NULL指针而不是参数的out引用inout。这样,调用者必须使用&可能被函数/方法修改的参数,并且更加明确。这适用于传递类和结构的实例。对于简单类型,首选按值传递。

于 2015-08-31T12:43:01.587 回答