注册 登录
编程论坛 C++教室

最近刚学c++,有个小疑问

绿茶盖儿 发布于 2011-11-16 23:19, 668 次点击
程序代码:

#include <iostream>
using namespace std;
class R
{
    public:
        R(int r1,int r2) {R1 = r1; R2 = r2;}
        R(R &r);
        ~ R() {}
        void print();
        void print() const;
    private:
        int R1,R2;
};

void R::print()
{
    cout<<R1<<":"<<R2<<endl;
}

R::R(R &r)
{
    R1 = r.R1;
    R2 = r.R2;
}

void R::print() const
{
    cout<<R1<<";"<<R2<<endl;
}

int main()
{
    R a(5,4);
    a.print();
    R const b(20,52);
    b.print();
    R aa(a);
    aa.print();
    R bb(b);      //这个地方有错误
    bb.print();
    return 0;
}


F:\myproject\c_program\exp1.cpp(39) : error C2558: class 'R' : no copy constructor available
Error executing cl.exe.

此处b是一个常对象,我想问一下错误原因是不是不能用常对象去初始化对象bb啊
2 回复
#2
xltc5002011-11-17 03:39
报错是因为你的R构造函数中的参数是非const引用,因而在函数的调用时只能传递非const变量,而你定义的b是const常量,因而导致错误。
#include <iostream>
using namespace std;
class R
{
    public:
        R(int r1,int r2) {R1 = r1; R2 = r2;}
        R(const R &r);
        ~ R() {}
        void print();
        void print() const;
    private:
        int R1,R2;
};

void R::print()
{
    cout<<R1<<":"<<R2<<endl;
}

R::R(const R &r)
{
    R1 = r.R1;
    R2 = r.R2;
}

void R::print() const
{
    cout<<R1<<";"<<R2<<endl;
}

int main()
{
    R a(5,4);
    a.print();
    R const b(20,52);
    b.print();
    R aa(a);
    aa.print();
    R bb(b);      //这个地方有错误
    bb.print();
    return 0;
}
#3
lucky5635912011-11-17 08:58
把bb定义为const对象就行
1