2015-02-24 32 views
0

我正在编写这个程序,我在其中定义了一个class X并手动定义了它的构造函数和析构函数,以便我可以在每个函数中都有一个print语句并查看它们何时被调用。定义我自己的拷贝构造函数

但是,问题似乎与我的复制构造函数的定义。

它提供了以下错误:

warning: passing const X as this argument of int X::getI() discards const

这是什么错误的原因是什么?一流的

代码片段:

class X { 
    public: 
     X() { 
      cout << "Default Constructor called\n"; 
      i = 0; 
     } 
     X(int i) { 
      cout << "Parameterized Constructor called\n"; 
      this->i = i; 
     } 
     X(const X& x) { 
      cout << "Copy Constructor called\n"; 
      i = x.getI(); 
     } 
     ~X() { 
      cout << "Destructor called\n"; 
     } 
     int getI() { 
      return i; 
     } 
    private: 
     int i; 
}; 
+0

如果我是从拷贝构造函数的参数去除常量它编译没有错误。 – 2015-02-24 05:53:04

+0

复制构造函数的参数应该是'const'。问题是'getI'不是。 – 5gon12eder 2015-02-24 05:54:19

+0

@ 5gon12eder:好的,但为什么复制构造函数应该有const? – 2015-02-24 06:04:01

回答

3

您尝试通过const引用调用非const成员函数getI。这是不允许的。由于getI不修改this对象,因此应声明为const

int 
getI() const 
{ 
    return this->i; 
} 

然后,即使通过const参考,您也可以调用它。

+0

那么,const引用或对象只能调用const函数? – 2015-02-24 06:04:40

+0

是的,因为通过'const'引用调用传递'const'' this'指针,同时将非'const'指针转换为'const'指针是一个隐式转换,相反的方向是不允许的(除非你使用一个非常丑陋的'const_cast')。如果你仔细想想,这是有道理的:你总是可以做一个额外的承诺,不要修改某些东西,但是你永远不能退出你已经做出的承诺。 – 5gon12eder 2015-02-24 06:08:11

1

getI()不是const成员函数。您不得在const对象上调用它。在复制构造函数中,xconst对象。因此,你不能叫

x.getI(); 

变化getI()const成员函数。

int getI() const { 
     return i; 
    } 
0
#include <iostream> 

using namespace::std; 


class X { 
    public: 
     X() { 
      cout << "Default Constructor called\n"; 
      i = 0; 
     } 


     X(int i) { 
      cout << "Parameterized Constructor called\n"; 
      this->i = i; 
     } 
     X(const X& x) { 
      cout << "Copy Constructor called\n"; 
      i = x.getI(); 
     } 
     ~X() { 
      cout << "Destructor called\n"; 
     } 
     int getI() const { 
      return i; 
     } 
    private: 
     int i; 
}; 

int main() 
{ 
} 

下面是正确的代码,我只好让格提为const

+1

谢谢Akhil。 – 2015-02-24 06:06:05