【问题标题】:Why does not see the array in the same class?为什么在同一个类中看不到数组?
【发布时间】:2014-04-24 07:26:49
【问题描述】:

我想写一个多项式类,每个多项式由多个 poly 组成,我用一个数组实现了它,如下代码:

class polynomial {

private:
    int count;

public: 
    polynomial() {
        count = 0;
        Term terms[10];
    }

    void create(int c) {
        terms[count].coef = c;
    }
};

class Term {

public:
    double coef;
    int expo;
};

我的 create 方法有问题,它不知道 term 数组并且不访问 Term 对象属性。为什么会这样?

【问题讨论】:

    标签: c++ arrays


    【解决方案1】:
    // First declare a class that will be referenced
    class Term {
    
    public:
        double coef;
        int expo;
    };
    
    class polynomial {
    
    private:
        int count;
        // terms should be a class member not a local of constructor
        Term terms[10];
    
    public: 
        polynomial() {
            count = 0;
            // If you declare terms array here 
            // it will be destroy after returns from constructor 
            // Term terms[10];
        }
    
        void create(int c) {
            terms[count].coef = c;
        }
    };
    

    如果您需要在 Term 声明之前进行多项式声明,则 前向声明 可以用作:

    class Term;
    
    class polynomial { ... };
    class Term { // Real declaration here };
    

    但这并不是在构造函数而不是类成员中撤销你错误的terms定义。

    【讨论】:

    • 谢谢。很有用
    【解决方案2】:

    探索“前向声明”方法。您需要先进行前向声明,然后才能在方法中使用 Term 类。这是因为当你编译 Polynomial 类时编译器不知道 Term 是什么,当你向前声明它时,编译器会继续前进,期望它稍后会得到 Term 的定义。

    class Term;
    
    class Polynomial{
    ..
    ..
    };
    
    class Term{
    ..
    ..
    };
    

    或者相反,在 Polynomial 类之前声明类 Term。

    【讨论】:

      【解决方案3】:

      您需要在使用之前声明一个类。所以交换 Term 和 polynomial 类,它应该编译得很好。请参阅以下示例:

      int main(){
          Foo foos[10];
      }
      
      class Foo {
      };
      // In function 'int main()':
      // error: 'Foo' was not declared in this scope
      

      class Foo {
      };
      
      int main(){
          Foo foos[10];
      }
      // compiles fine
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2011-03-21
        • 1970-01-01
        相关资源
        最近更新 更多