繁体   English   中英

C ++-错误:未在此范围内声明“函数”

[英]C++ - error: 'function' was not declared in this scope

我有以下问题:错误:在此范围内未声明'kleiner'我的教授告诉我,我的代码对他而言还行。 目录全部包含在bulid选项中(我正在使用Code :: Blocks)。 有人可以告诉我可能是什么问题吗?

main.cpp中

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

int main(int argc, char *argv[])
{
    Vector v1;
    cout << "v1: " << v1 << endl;

    Vector v2(8);
    cout << "v2: " << v2 << endl;
    cout << "Minimum von v2: " << v2.min() << endl;

    Vector v3(v2);
    cout << "v3: " << v3 << endl;
    cout << "Anzahl von v3: " << v3.getAnzahl() << endl;

    if ( kleiner( v3[2], v2[5] ) )//<<--<<--<<-- HERE IS THE PROBLEM
        cout << v3[2] << " ist kleiner als " << v2[5] << endl;

    int arr[5] = { 10, 5, 2, 3, 12 };

    Vector v4;
    cout << "v4: " << v4 << endl;
    v4.setVector( arr, 4 );
    cout << "v4 nach set: " << v4 << endl;
    cout << "Minimum von v4: " << v4.min() << endl;
    cout << "Anzahl von v4: " << v4.getAnzahl() << endl;

    return 0;
}

vector.h

#ifndef VECTOR_H
#define VECTOR_H

#include <iostream>
using namespace std;

class Vector
{
      int* v;
      int anzahl;

public:
       Vector(int anzahl = 10);
       Vector( const Vector& vec ); // Kopierkonstruktor
       ~Vector();
       friend bool kleiner( const int& a, const int& b );
       int min() const;
       int getAnzahl() const;
       int operator[]( const int i ) const;
       void setVector( int* sv, int sanzahl);
       friend ostream& operator<< ( ostream& os, const Vector& v );
};

#endif

vector.cpp

#include "vector.h"

Vector::Vector( int a ) : anzahl(a)
{
    v = new int[a];
    for ( int i = 0; i < a; i++ )
        v[i] = i;
}

Vector::Vector( const Vector& vec )
{
    anzahl = vec.getAnzahl();
    v = new int[anzahl];
    for ( int i = 0; i < anzahl; i++ )
        v[i] = vec[i];
}

Vector::~Vector()
{
    delete[] v;
    v = NULL;
}

bool kleiner( const int& a, const int& b )
{
     return ( a < b );
}

int Vector::min() const
{
     int min = v[0];
     for ( int i = 1; i < anzahl; i++ )
     {
         if ( v[i] < min )
             min = v[i];
     }
     return min;
}

int Vector::getAnzahl() const
{
    return anzahl;
}

int Vector::operator[] ( const int i ) const
{
    return v[i];
}

void Vector::setVector( int* sv, int sanzahl )
{
     delete[] v; // alten Inhalt loeschen
     anzahl = sanzahl;
     v = new int[anzahl];
     for ( int i = 0; i < anzahl; i++ )
     v[i] = sv[i];
     return;
}

ostream& operator<< ( ostream& os, const Vector& v )
{
     for ( int i = 0; i < v.anzahl; i++ )
         os << v[i] << ", ";
     return os;
}

在类之外声明该函数,并指定为朋友。

参考; http://en.cppreference.com/w/cpp/language/friend

首先在类或类模板X的朋友声明中声明的名称成为X的最内层封闭名称空间的成员,但不可用于查找(考虑X的依赖于参数的查找除外),除非名称空间范围内的匹配声明为提供-有关详细信息,请参见名称空间。

我认为您和您的教授有不同的编译器?

在标头中的类定义之外也声明Friend函数。 直到将其在类外声明之前,它才可见。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM