【问题标题】:void Test::printxy(void)' : cannot convert 'this' pointer from 'const Test' to 'Test &' in const classvoid Test::printxy(void)' : 不能在 const 类中将 'this' 指针从 'const Test' 转换为 'Test &'
【发布时间】:2013-12-14 22:16:26
【问题描述】:

我编写了一个关于 const 类的非常简单的程序,但是,当我编译时,出现错误:void Test::printxy(void)' : cannot convert 'this' pointer from 'const Test' to 'Test & '

程序如下

#include <iostream>
using namespace std;
class  Test
{
private:
    int x, y;
public:
    Test(int a = 1, int b = 1) : x(a), y(b) {};
    void printxy();
};
void Test::printxy()
{
    cout << "x*y=" << x*y << endl;
}
void main(void)
{
    const Test t;
    t.printxy();
    system("pause");
}

【问题讨论】:

  • 为什么这个网站有这么多问题都用void main
  • @remyabel :我自己也想知道。甚至 Herbert Schildt 的书(至少我可以在 amazon.com 上看到的那部分)都说对了。

标签: c++ class constants


【解决方案1】:

由于printxy 成员函数未声明const,因此无法在常量对象上调用它。你需要像这样声明成员函数const

class Test
{
    void printxy() const;
    //             ^^^^^

    // ...
};

void Test::printxy() const
{
    // ...
}

【讨论】:

    【解决方案2】:

    您尝试在const 对象t 上调用非const 函数printxy()。您在方法声明后缺少const

    class Test {
        // ...
        void printxy() const;
    };
    
    void Test::printxy() const {
        // ...
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2015-09-11
      • 1970-01-01
      • 1970-01-01
      • 2010-12-14
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多