无法通过引用传递常量对象

时间:2013-06-10 23:33:14

标签: c++ object pass-by-reference

我正在通过引用练习类声明/实现/传递对象。这是我的主类,头文件和其他类的代码:

//Header file (Circle2.h)
#ifndef CIRCLE_H
#define CIRCLE_H

class Circle{
    private:
        double radius;

    public:
        Circle();
        Circle(double newRadius);
        double getArea() const;
        double getRadius() const;
        void setRadius(double newRadius);
};
#endif

//Main class (PassObjectByReference.cpp)
#include <iostream>
#include "Circle2.h"
using namespace std;

void printCircle(const Circle &c){
    cout << "The area of the circle of " << c.getRadius() << " is " << c.getArea() << endl;
}

int main(){
    Circle myCircle(5.0);
    printCircle(&myCircle);

    return 0;
}

//Other class (Circle2.cpp)
#include "Circle2.h"

Circle::Circle(){
    radius = 1;
}

Circle::Circle(double newRadius){
    radius = (newRadius >= 0) ? newRadius : 0;
}

double Circle::getRadius() const{
    return radius;
}

double Circle::getArea() const{
    return radius * radius * 3.14159;
}

void Circle::setRadius(double newRadius){
    radius = (newRadius >= 0) ? newRadius : 0; 
}

当我尝试编译时,我得到了这两个错误:

PassObjectByReference.cpp:在函数'int main()'中: PassObjectByReference.cpp:11:错误:从'Circle *'类型的表达式初始化'const Circle&amp;'类型的引用无效 PassObjectByReference.cpp:5:错误:传递'void printCircle(const Circle&amp;)'的参数1

我无法找到错误。任何帮助将不胜感激。 谢谢!

2 个答案:

答案 0 :(得分:8)

int main(){
    Circle myCircle(5.0);
    printCircle(&myCircle); // You are passing a pointer.
    return 0;
}

正确的陈述是:

printCircle(myCircle);

答案 1 :(得分:2)

删除& - 将其变成指针,这不是你想要的。你应该写:

printCircle( myCircle );