开发者

Copy Constructors and calling functions

开发者 https://www.devze.com 2022-12-27 11:54 出处:网络
I\'m trying to call an accessor function in a copy constructor but it\'s not working.Here\'s an example of my problem:

I'm trying to call an accessor function in a copy constructor but it's not working. Here's an example of my problem:

A.h

class A {

public:
    //Constructor
    A(int d);
    //Copy Constructor
    A(const A &rhs);

    //accessor for data
    int getData();

    //mutator for data
    void setData(int d);

private:
    int data;
};

A.cpp

#include "A.h"

//Constructor
A::A(int d) {
    this->setData(d);
}

//Copy Constructor
A::A(const A &rhs) {
    this->setData(rhs.getData()); 
}

//accessor for data
int A::getData() {
    return data;
}

//mutator for data
void A::setData(int d) {
    data = d;
}

When I try to compile this, I get the following error:

error: passing 'const A' 开发者_如何学JAVAas 'this' argument of 'int A::getData()' discards qualifiers

If I change rhs.getData() to rhs.data, then the constructor works fine. Am I not allowed to call functions in a copy constructor? Could somebody please tell me what I'm doing wrong?


The problem is rhs is declared as const, but getData() isn't, so it could be modifying rhs when you call it even though rhs is supposedly const. As getData() is an accessor, it should be const too:

//accessor for data
int getData() const;


Your "accessor" can only be called on non-const objects, because it isn't marked const. You should declare it:

int getData() const;

Then you're allowed to call it on rhs, which is a const reference.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号