相关疑难解决方法(0)

堆栈上的多态对象?

之前的一个问题中, 我引用了Stroustrup,了解为什么所有类的公共Object类在c ++中都存在问题.在该引文中有声明:

使用通用基类意味着成本:对象必须被堆分配为多态的;

我真的没有看过两次,因为它在Bjarnes的主页上,我想很多眼睛都会扫描那句话并报告任何错误陈述.

然而,一位评论者指出,情况可能并非如此,回想起来,我找不到任何理由这样做的理由.一个简短的测试用例产生了"VDerived :: f()"的预期结果.

struct VBase
{
    virtual void f()    { cout<<"VBase::f()"<<endl; }
};

struct VDerived:VBase
{
    void f()  { cout<<"VDerived::f()"<<endl; }
};

void test(VBase& obj){
    obj.f();
}

int main(int argc, char** argv) {
    VDerived obj;
    test(obj);
    return 0;
}
Run Code Online (Sandbox Code Playgroud)

当然,如果测试的形式参数test(VBase obj)是完全不同的,但这不是堆栈与堆参数,而是复制语义.

Bjarne是错误还是我错过了什么?

c++ polymorphism

30
推荐指数
2
解决办法
6701
查看次数

通过参考传递结构

#include <stdio.h>
#include <math.h>


struct coeff
{
    int a;
    int b;
    int c;
};


struct roots
{
    double r1;
    double r2;
};


void calculateRoots(struct coeff*, struct roots*);


int main(int argc, char const *argv[])
{
    struct coeff *c;
    struct roots *r;
    c = NULL;
    r = NULL;

    c->a = 10;
    c->b = 20;
    c->c = 30;

    calculateRoots(c,r);

    printf("The roots are : %lf & %lf\n", r->r1, r->r2);

    return 0;
}


void calculateRoots(struct coeff *cef, struct roots *rts)
{
    rts->r1 = (-(cef->b) + …
Run Code Online (Sandbox Code Playgroud)

c struct pass-by-reference

1
推荐指数
1
解决办法
90
查看次数

标签 统计

c ×1

c++ ×1

pass-by-reference ×1

polymorphism ×1

struct ×1