访问类实例的成员时出错 [英] Error when accessing members of an instance of a class

查看:112
本文介绍了访问类实例的成员时出错的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在学习c ++,所以我很难修复我编译这个程序时出现的错误。我要写一个小程序,可以打印每个元素在一个int数组。例如,NumberRange类有两个参数a和b,如果a是5,b是9,那么构造函数将分配一个数组,并按照顺序填充值5,6,7,8,9。我有我的代码如下:
头文件 NumberRange.h

I am learning c++, so it is hard for me to fix the errors I have when I compile this program. I am going to write a small program which can print every elements in an int array. For instance, class NumberRange has two arguments a and b, if a is 5 and b is 9, then the constructor would allocate an array and fill it with the values 5,6,7,8,9 in that order. I have my code following: the head file NumberRange.h

class NumberRange {
public:
    NumberRange(int a, int b);
    virtual ~NumberRange();
    void Print(int a, int b);
private:
    int *range_;
    int size;
};

.cc档案 NumberRange.cc

#include <iostream>
#include "numberrange.h"
using namespace std;

NumberRange::NumberRange(int a, int b) {
    if (a > b) {
        cout << "a must be equal or less than b" << endl;
    }
}

NumberRange::~NumberRange() {
     //implementation
}

void NumberRange::Print(int a, int b) {
     this->size = b - a + 1;
     this->range_[0] = a;
     for (int i = 0; i < this->size; i++) {
         this->range_[i] = a + i;
         cout << this->range_[i] << endl;
     }
}

int main() {
    NumberRange *numberrange;
    numberrange->NumberRange (5, 9);
    numberrange->Print(5,9);
}



我在编译程序时遇到错误:
不能在带有' - >'号码范围 - > NumberRange(5,9)的'NumberRange'中引用类型成员'NumberRange';

成员'NumberRange'声明在这里class NumberRange {

我不知道错误意义和如何解决这个程序?我想知道逻辑是对的还是不对。有没有人可以帮助我?非常感谢。

I don't know the errors meaning and how can I fix this program? I am wondering the logic is right or not as well. Is there anyone can help me? Thank you so much.

推荐答案

NumberRange *numberrange;
numberrange->NumberRange (5, 9);

这不是你如何构造一个新的 NumberRange 。您可以执行

This is not how you construct a new NumberRange. You can do either

NumberRange *numberrange = new NumberRange(5, 9);

或者更好地避免多余的内存分配:

Or better yet, avoid the superfluous memory allocation:

NumberRange numberrange(5, 9);

这篇关于访问类实例的成员时出错的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆